Reflecting a private field from a base class

前端 未结 5 1176
爱一瞬间的悲伤
爱一瞬间的悲伤 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 08:10

    Extension method:

    /// 
    /// Returns the FieldInfo matching 'name' from either type 't' itself or its most-derived 
    /// base type (unlike 'System.Type.GetField'). Returns null if no match is found.
    /// 
    public static FieldInfo GetPrivateField(this Type t, String name)
    {
        const BindingFlags bf = BindingFlags.Instance | 
                                BindingFlags.NonPublic | 
                                BindingFlags.DeclaredOnly;
    
        FieldInfo fi;
        while ((fi = t.GetField(name, bf)) == null && (t = t.BaseType) != null)
            ;
        return fi;
    }
    

提交回复
热议问题