簡體   English   中英

使用反射從覆蓋中獲取價值

[英]Get Value from Override using Reflection

我想從繼承的 class 的虛擬屬性中獲取值,請參見下面的代碼:

底座 class:

public class TestBaseClass
{
   public virtual int Index { get; }
}

繼承 class:

public class TestInheritedClass : TestBaseClass
{
   public override int Index => 100; // I want to get this value using reflection
}

我的代碼:

static void Main(string[] args) 
{
   var assemblies = Assembly.LoadFile(args[0]);
   foreach(var type in assembly.ExportedTypes)
   {
      if(type.IsSubclassOf(typeof(TestBaseClass))
      {
         foreach(var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
         {
            var value = prop.GetValue(typeof(int), null); // I expect to return 100 from override Index value
         }
      }
   }
}

我錯過了什么還是我做錯了? 我正在嘗試從虛擬屬性中獲取值100 有沒有辦法獲得價值?

有沒有辦法獲得價值?

是的,有辦法。 讓我們先看看你在那里做了什么:

prop.GetValue(typeof(int), null)

您正在使用PropertyInfo.GetValue 重載。 它期望 object 的實例從中獲取值作為第一個參數。 相反,您正在傳遞typeof(int) 這不是TestInheritedClass的一個實例。 我將忽略這里的第二個參數,因為我們不是在談論索引器。 您可以在文檔中閱讀有關該參數的信息。

相反,您必須先創建一個TestInheritedClass的實例:

var instance = Activator.CreateInstance(typeof(TestInheritedClass));

然后像這樣使用它:

if (type.IsSubclassOf(typeof(TestBaseClass))
{
    var instance = Activator.CreateInstance(type);

    foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
    {
       var value = prop.GetValue(instance);
    }
}

暫無
暫無

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

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