反思没有的getter / setter? [英] Reflection without a Getter/Setter?
问题描述
如果我在类中声明如下:
私人诠释?身份识别码= NULL;
和然后尝试通过反射来访问它,它会不能够找到它。我的意思是,下面将设置gProp为null:
GTYPE = refObj.GetType();
gProp = gType.GetProperty(属性名,System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
不过,它会正常工作,如果我,而不是将它声明为:
私人诠释? MYID {获得;组; }
这是不足为奇给我,因为我已经知道这是事实。不过,我想确认;反正是有使与反思第一次申报工作,或者我必须为了反映工作提供的getter / setter?
谢谢!
您需要的 getfield命令
方法,而不是(的getProperty
)的字段。
Type.GetFields法 搜索指定字段,使用指定绑定约束。
示例
//您的实例
为MyObject例如=新的MyObject();
//获取类型信息
MyType类型=的typeof(myObject的);
//获得字段信息
字段信息字段信息= myType.GetField(身份识别码);
//设置一些价值
fieldInfo.SetValue(例如,123);
//获得字段值
VAR值= fieldInfo.GetValue(实例);
//值为123
更多信息
If I declare the following in my class:
private int? MyID = null;
And then attempt to access it via reflection, it won't be able to find it. What I mean by that is, the below will set gProp to null:
gType = refObj.GetType();
gProp = gType.GetProperty(PropertyName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
However, it will work fine if I instead declare it as:
private int? MyID { get; set; }
This isn't at all surprising to me as I already knew this to be the case. However, I wanted to confirm; is there anyway to make the first declaration work with reflection, or do I have provide a Getter/Setter in order for reflection to work?
Thanks!
You need the GetField
method (instead of GetProperty
) for Fields.
Type.GetFields Method Searches for the specified field, using the specified binding constraints.
Sample
// 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
More Information
- MSDN - Type.GetField Method (String, BindingFlags)
- MSDN - SetField Method (String, BindingFlags, Object)
这篇关于反思没有的getter / setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!