Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中找到泛型类的属性?_C#_Generics_Reflection - Fatal编程技术网

如何在C#中找到泛型类的属性?

如何在C#中找到泛型类的属性?,c#,generics,reflection,C#,Generics,Reflection,我有以下课程: [Msg(Value = "YaaY")] public class PersonContainer<T>  where T : new() {    ... } public class HappyPerson {    ... } [Msg(Value = "NaaY")] public class SadPerson {    ... } 但是,我只获得“PersonContainer”(即“YaaY”)的属性如何在运行时获得T(HappyPerson[

我有以下课程:

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


public class HappyPerson
{
   ...
}

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

但是,我只获得“PersonContainer”(即“YaaY”)的属性如何在运行时获得
T(HappyPerson[if any]或SadPerson[“NaaY”])
的属性,而不知道T是什么?

您需要获得泛型参数的类型以及它的属性:

var info = personContainer.GetType();

if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}

编辑:
GetGenericArguments
返回一个
Type
数组,因此我对
GetType
的第一次调用是不必要的,我将其删除。

您需要获取泛型参数的类型,然后是它的属性:

var info = personContainer.GetType();

if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}

编辑:
GetGenericArguments
返回一个
Type
数组,因此我对
GetType
的第一次调用是不必要的,我将其删除。

您需要循环遍历泛型类型参数以获取其属性:

var info = personContainer.GetType();

if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}

您需要循环遍历泛型类型参数以获取其属性:

var info = personContainer.GetType();

if (info.IsGenericType)
{
     var attributes = (MsgAttribute[])info.GetGenericArguments()[0]
                      .GetCustomAttributes(typeof(MsgAttribute), false);
}
var info = personContainer.GetType();
foreach (var gta in info.GenericTypeArguments)
{
    // gta.GetCustomAttributes(...)
}

可能重复的可能重复的可能重复的谢谢你的回答。谢谢你的回答。