Reflecting a private field from a base class

前端 未结 5 1280
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 07:34

Here is the structure:

MyClass : SuperClass2

SuperClass2 : SuperClass1

superClass2 is in Product.Web and SuperClass1 is in the .NET System.Web assemb

5条回答
  •  清歌不尽
    2020-11-29 07:57

    You can manually go up in the inheritance chain to get the base fields:

    Given these classes:

    class SuperClass1
    {
        private int myField;
    }
    
    class SuperClass2 : SuperClass1
    {
    }
    
    class MyClass : SuperClass2
    {
    
    }
    

    This should work:

    var myObj = new MyClass();
    var myField = typeof(MyClass).BaseType
                                 .BaseType
                                 .GetField("myField", BindingFlags.Instance | BindingFlags.NonPublic);
    

    There's a more generic solution in this SO answer: Not getting fields from GetType().GetFields with BindingFlag.Default

提交回复
热议问题