C# Reflection - changing the value of a field of a variable

后端 未结 3 440
轮回少年
轮回少年 2021-01-01 01:40

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 c

3条回答
  •  青春惊慌失措
    2021-01-01 02:07

    Yes, its possible.

    In short, do something like

    Type typeInQuestion = typeof(TypeHidingTheField);
    FieldInfo field = typeInQuestion.GetField("FieldName", BindingFlags.NonPublic | BindingFlags.Instance);
    field.SetValue(instanceOfObject, newValue);
    

    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.

    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.

    Look over System.Reflection for reference.

提交回复
热议问题