Can C# extension methods access private variables?

前端 未结 7 1004
借酒劲吻你
借酒劲吻你 2021-02-01 11:49

Is it possible to access an object\'s private variables using an extension method?

7条回答
  •  无人及你
    2021-02-01 12:18

    Use Reflection

    Not recommended, but you could possibly access any private variable of any type using another extension method like so:

    public static T GetFieldValue(this object obj, string name) {
        var field = obj.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        return (T)field?.GetValue(obj);
    }
    

    And then access a private field of an arbitrary type:

    Foo foo = new Foo();
    string privateBar = foo.GetFieldValue("_bar");
    

提交回复
热议问题