簡體   English   中英

如何使用反射訪問私有基類字段

[英]How to access a private base class field using Reflection

我正在嘗試在BaseClass類型的變量上設置私有的“可見”字段。

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

我已經成功訪問​​了ChildClass類型的變量,以及BaseClass上“ visible”字段的FieldInfo。

但是,當我嘗試設置/獲取字段的值時,出現錯誤System.Runtime.Remoting.RemotingException:遠程處理無法在類型'BaseClass'上找到字段'visible'。

那么,是否有一種方法可以將“ 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  
{
}

你可以這樣嘗試

    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

以下是一些代碼,演示了獲取字段與屬性之間的區別:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM