没有Getter/Setter的反思?

Nul*_*rty 1 .net c# reflection runtime properties

如果我在课堂上声明以下内容:

private int? MyID = null;
Run Code Online (Sandbox Code Playgroud)

然后尝试通过反射访问它,它将无法找到它.我的意思是,下面将gProp设置为null:

gType = refObj.GetType();
gProp = gType.GetProperty(PropertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)

但是,如果我将其声明为:

private int? MyID { get; set; }
Run Code Online (Sandbox Code Playgroud)

这对我来说并不奇怪,因为我已经知道这是事实.但是,我想证实一下; 无论如何,使用反射使第一个声明工作,或者我是否提供了一个Getter/Setter以使反射起作用?

谢谢!

Pac*_*civ 9

它是一个字段,而不是属性,因此它不会被返回GetProperty.你需要使用GetField方法.


dkn*_*ack 5

你需要Field 的GetField方法(而不是GetProperty).

Type.GetFields方法 使用指定的绑定约束搜索指定的字段.

样品

// your instance
MyObject instance = new MyObject();
// get type information
Type myType = typeof(MyObject);
// get field information
FieldInfo fieldInfo = myType.GetField("MyID");
// set some value
fieldInfo.SetValue(instance, 123);
// get field value
var value = fieldInfo.GetValue(instance);
// value is 123
Run Code Online (Sandbox Code Playgroud)

更多信息