Find a private field with Reflection?

前端 未结 10 1192
自闭症患者
自闭症患者 2020-11-22 16:17

Given this class

class Foo
{
    // Want to find _bar with reflection
    [SomeAttribute]
    private string _bar;

    public string BigBar
    {
        ge         


        
10条回答
  •  失恋的感觉
    2020-11-22 16:48

    Get private variable's value using Reflection:

    var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);
    

    Set value for private variable using Reflection:

    typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue");
    

    Where objectForFooClass is a non null instance for the class type Foo.

提交回复
热议问题