簡體   English   中英

如何在C#中找到泛型類的屬性?

[英]How can I find the attributes of a generic class in C#?

我有以下課程:

[Msg(Value = "YaaY")]
public class PersonContainer<T>  where T : new()
{
   ...
}


public class HappyPerson
{
   ...
}

[Msg(Value = "NaaY")]
public class SadPerson
{
   ...
}

使用以下方法,我可以獲取“ PersonContainer”的屬性:

public void GetMsgVals(object personContainer)
{
    var info = personContainer.GetType();

    var attributes = (MsgAttribute[])info.GetCustomAttributes(typeof(MsgAttribute), false);
    var vals= attributes.Select(a => a.Value).ToArray();        
}

但是,我僅獲得“ PersonContainer”的屬性(即“ YaaY”),如何在運行時獲得T (HappyPerson [if any] or SadPerson["NaaY"])的屬性T (HappyPerson [if any] or SadPerson["NaaY"])而又不知道T是什么?

您需要獲取通用參數的類型,然后是屬性:

var info = personContainer.GetType();

if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}

編輯: GetGenericArguments返回一個Type數組,因此我對GetType第一次調用是不必要的,因此將其刪除。

您需要遍歷泛型類型參數以獲取其屬性:

var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}

暫無
暫無

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

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