Getting a property reference using reflection

纵然是瞬间 提交于 2020-02-03 07:23:30

问题


var a = new obj();
var property = a.GetType().GetProperty("DB").GetValue(a,null) as testObject;

does this mean that the variable property hold a reference to the the same object that i got in object a , or a new testObject was made that holds the same values?

if this means creating a new object, then how can i get the reference to that property/backing field using reflection?


回答1:


property now holds a referece to whatever is in a's DB property.

I'm not sure though what happens when you call GetValue() on a property that has a value type, I suppose you get a reference to a boxed copy of the original value, as explained in Boxing and Unboxing (C# Programming Guide):

Boxing a value type [to object in GetValue()'s case] allocates an object instance on the heap and copies the value into the new object.




回答2:


Variable property holds reference to same value stored in property DB.

GetValue(a,null) return type is object so with as operator you are simple type casting it.




回答3:


It means a value of a property DB of your object a cast to testType (you pass a reference to object a in PropertyInfo.GetValue), so there is only one object a and your variable references its DB property.



来源:https://stackoverflow.com/questions/20871744/getting-a-property-reference-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!