本文实例讲述了go语言通过反射获取和设置结构体字段值的方法.分享给大家供大家参考.具体实现方法如下: type MyStruct struct { N int } n := MyStruct{ 1 } // get immutable := reflect.ValueOf(n) val := immutable.FieldByName("N").Int() fmt.Printf("N=%d\n", val) // prints 1 // set mutable :=…
本文告诉大家多个不同的方法使用反射获得私有属性,最后通过测试性能发现所有的方法的性能都差不多 在开始之前先添加一个测试的类 public class Foo { private string F { set; get; } = "123"; } 如果需要拿到 Foo 的 属性 F 可以通过 PropertyInfo 直接拿到,从一个类拿到对应的 PropertyInfo 可以通过下面的代码 var foo = new Foo(); var type = foo.GetType(); c…
获取所有字段的值: public void PrintProperties(Object obj) { Type type = obj.GetType(); foreach( PropertyInfo p in type.GetProperties()) { Console.Write(p.GetValue()); } }…