簡體   English   中英

如何在沒有具體實例的情況下使用Reflection來獲取Type的靜態屬性的值

[英]How can I use Reflection to get the value of a Static Property of a Type without a concrete instance

考慮以下課程:

public class AClass : ISomeInterface
{
    public static int AProperty
    {
   get { return 100; } 
    }
}

然后我有另一個課程如下:

public class AnotherClass<T>
   where T : ISomeInterface
{

}

我通過以下方式實例:

AnotherClass<AClass> genericClass = new  AnotherClass<AClass>();

如何在沒有具體的AClass實例的情況下從我的genericClass中獲取AClass.AProperty的靜態值?

就像是

typeof(AClass).GetProperty("AProperty").GetValue(null, null)

會做。 不要忘記轉換為int

文檔鏈接: http//msdn.microsoft.com/en-us/library/b05d59ty.aspx (他們也有靜態屬性的例子。)但是如果你確切地知道AClass ,你可以只使用AClass.AProperty

如果你在T = AClass AnotherClass<T> T = AClass ,你可以將它稱為T

typeof(T).GetProperty("AProperty").GetValue(null, null)

如果你確定你的T具有靜態屬性AProperty ,這將有效。 如果無法保證任何T上存在此類屬性,則需要在途中檢查返回值/異常。

如果只有AClass對你感興趣,你可以使用類似的東西

if (typeof(T) == typeof(AClass))
    n = AClass.AProperty;
else
    ???

首先獲取您的AnotherClass實例的泛型類型。

然后獲取靜態屬性。

然后獲取屬性的靜態值。

// I made this sealed to ensure that `this.GetType()` will always be a generic
// type of `AnotherClass<>`.
public sealed class AnotherClass<T>
{
    public AnotherClass(){
        var aPropertyValue = ((PropertyInfo)
                this.GetType()
                    .GetGenericArguments()[0]
                    .GetMember("AProperty")[0])
            .GetValue(null, null);
    }
}

當然,認識到不可能確保存在“AProperty”,因為接口不能用於靜態簽名,我將ISomeInterface刪除為與解決方案無關。

暫無
暫無

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

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