Reflecting a private field from a base class

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

    In a similar vein to BrokenGlass's solution, you could do this to make it a bit more generic:

    class Base { private int _baseField; }
    class Derived : Base { }
    class Mine : Derived { }
    

    And then:

    Type t = typeof(Mine);
    FieldInfo fi = null;
    
    while (t != null) 
    {
        fi = t.GetField("_baseField", BindingFlags.Instance | BindingFlags.NonPublic);
    
        if (fi != null) break;
    
        t = t.BaseType; 
    }
    
    if (fi == null)
    {
        throw new Exception("Field '_baseField' not found in type hierarchy.");
    }
    

    As a utility method:

    public static void SetField(object target, string fieldName, object value)
    {
        if (target == null)
        {
            throw new ArgumentNullException("target", "The assignment target cannot be null.");
        }
    
        if (string.IsNullOrEmpty(fieldName))
        {
            throw new ArgumentException("fieldName", "The field name cannot be null or empty.");
        }
    
        Type t = target.GetType();
        FieldInfo fi = null;
    
        while (t != null)
        {
            fi = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
    
            if (fi != null) break;
    
            t = t.BaseType; 
        }
    
        if (fi == null)
        {
            throw new Exception(string.Format("Field '{0}' not found in type hierarchy.", fieldName));
        }
    
        fi.SetValue(target, value);
    }
    

    And then:

    Mine m = new Mine();
    
    SetField(m, "_baseField", 10);
    

提交回复
热议问题