C#反思 - 改变一个变量的字段的值 [英] C# Reflection - changing the value of a field of a variable
问题描述
我有一个类的实例,我想由于我的系统约束来改变这种情况下的仅与同类型(交换),
的另一个对象的对象数据成员我不能使用=,新的或setter操作。
I have an instance of a class, I want to change an object data member of this instance only with another object of the same type (swap), due to my system constraints i can't use =,new or setter operators.
基本上我想改变一个变量的字段的值,该字段是包含在其他对象对象 - 的变量,它的实例我有
Basically I would like to change the value of a field of a variable, the field is an object contained inside another object - the variable which its instance I have.
使用反射这可能吗?如果是这样有人可以请给我基本方向?
is it possible using reflection? if so can someone please give me basic direction?
由于
约阿夫
推荐答案
是的,其可能的。
在短,做这样的事情。
Type typeInQuestion = typeof(TypeHidingTheField);
FieldInfo field = typeInQuestion.GetField("FieldName", BindingFlags.NonPublic | BindingFlags.Instance);
field.SetValue(instanceOfObject, newValue);
要改变一个隐藏的(私有/保护/内部)字段的值。使用相应的 FieldInfo.GetValue(...)
阅读;将二者结合起来,以平凡得到您想要的交换操作。
to change the value of a hidden (private/protected/internal) field. Use the corresponding FieldInfo.GetValue(...)
to read; combine the two trivially to get your desired swapping operation.
不要把我抱到的BindingFlags(我好像总是让那些错误的首次尝试)或确切的语法,但是这基本上它。
Don't hold me to the BindingFlags (I always seem to get those wrong on the first attempt) or the exact syntax, but that's basically it.
在看的参考的System.Reflection 。
这篇关于C#反思 - 改变一个变量的字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!