首页 新闻 会员 周边

反射获取泛型Attribute

0
悬赏园豆:20 [已解决问题] 解决于 2009-04-06 00:27

   [AttributeUsage(AttributeTargets.GenericParameter),Serializable]
    public class A : Attribute
    {
    }

    public class B <[A]T>
    {
    }

    Type type = typeof(B <string>);
   

怎么根据type获取类型为A的CustomAttribute对象

希望的田野的主页 希望的田野 | 初学一级 | 园豆:180
提问于:2009-04-05 01:28
< >
分享
最佳答案
0
Code
Type def = typeof(B<>);

//获取类型 B 的所有范型参数类型
Type[] defparams = def.GetGenericArguments();

foreach(Type tp in defparams)
{
//获取范型参数的所有自定义特性
object[] cstAttributes = tp.GetCustomAttributes(false);

foreach(object cstAttr in cstAttributes)
{
//输出自定义特性的名称
Console.WriteLine("Your Custom Attribute is {0}",cstAttr);
}
}
Launcher | 高人七级 |园豆:45045 | 2009-04-05 14:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册