【问题标题】:How to access a private base class field using Reflection如何使用反射访问私有基类字段
【发布时间】:2012-01-23 19:46:54
【问题描述】:

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

  • 子类
    • 基类
      • “可见”字段

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

但是当我尝试设置/获取字段的值时,我收到错误 System.Runtime.Remoting.RemotingException: Remoting cannot find field 'visible' on type 'BaseClass'。

那么有没有办法将 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  
{
}

【问题讨论】:

  • 你能发布你的类的定义,以及你正在使用的反射代码吗?
  • 您似乎将问题中的“财产”和“领域”这两个术语混为一谈。你确定你在寻找正确的东西吗?
  • 您在问题中混合了术语字段和属性。它们是不同的概念,反射提供了不同的方法来访问它们的定义(例如 GetProperties() 与 GetFields())。我的猜测是您的可见字段实际上被定义为属性。
  • 如果你有一个 CalcScene 的实例,为什么不创建一个公共的 Visible 属性并且不使用反射?
  • @jrummell - 我正在使用反射来编辑我正在使用的第 3 方组件中的值。所以我显然不能更改源代码!

标签: c# .net reflection types casting


【解决方案1】:

你可以这样试试

    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);
        }
    }

生产

我的属性 2 我的财产

【讨论】:

  • 如果两个属性都是私有的怎么办?
  • @Jenko 你能看看这个链接stackoverflow.com/questions/2267277/…
  • 有效吗?我试过了,但我无法让它工作。你有更多信息吗?我收到错误“远程处理在 BaseClas 类型上找不到“可见”字段”...你知道为什么吗?
【解决方案2】:

以下代码演示了获取字段与获取属性之间的区别:

  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;
  }

【讨论】:

  • 谢谢,但 FieldInfo 是一个非空值!我已经能够访问“可见”属性的字段了!
  • 哦,我明白了。您正在尝试使用反射在基类上设置私有字段值。没听懂。您的代码是否完全受信任和/或具有正确的权限? msdn.microsoft.com/en-us/library/6z33zd7h.aspx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多