如何使用Reflection访问私有基类字段

时间:2011-12-19 18:00:30

标签: c# .net reflection types casting

我正在尝试在BaseClass类型的变量上设置私有“可见”字段。

  • ChildClass
    • 的BaseClass
      • “可见”字段

我已经成功访问​​了ChildClass类型的变量,以及BaseClass上“visible”字段的FieldInfo。

但是当我尝试设置/获取字段的值时,我得到错误 System.Runtime.Remoting.RemotingException:Remoting在类型'BaseClass'上找不到字段'visible'。 < / p>

那么有没有办法将ChildClass类型的变量“向下转换”为BaseClass以使反射有效?


修改:我正在使用的确切代码:

// get the varible
PropertyInfo pi = overwin.GetProperty("Subject", BindingFlags.Instance|BindingFlags.Public);
CalcScene scene = (CalcScene) pi.GetValue(inwin, null);

// <<< scene IS ACTUALLY A TYPE OF DisplayScene, WHICH INHERITS FROM CalcScene

// get the 'visible' field
Type calScene = typeof(CalcScene);
FieldInfo calVisible = calScene.GetField("visible",BindingFlags.Instance|BindingFlags.NonPublic);

// set the value
calVisible.SetValue(scene, true); // <<< CANNOT FIND FIELD AT THIS POINT

确切的类结构:

class CalcScene  
{
    private bool visible;
}

class DisplayScene : CalcScene  
{
}

2 个答案:

答案 0 :(得分:3)

你可以这样尝试

    class B
    {
        public int MyProperty { get; set; }
    }

    class C : B
    {
        public string MyProperty2 { get; set; }
    }

    static void Main(string[] args)
    {
        PropertyInfo[] info = new C().GetType().GetProperties();
        foreach (PropertyInfo pi in info)
        {
            Console.WriteLine(pi.Name);
        }
    }

产生

    MyProperty2
    MyProperty

答案 1 :(得分:1)

以下是一些代码,用于演示获取字段与属性之间的区别:

  public static MemberInfo GetPropertyOrField(this Type type, string propertyOrField)
  {
      MemberInfo member = type.GetProperty(propertyOrField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
      if (member == null)
          member = type.GetField(propertyOrField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

      Debug.Assert(member != null);
      return member;
  }