GetCustomAttribute 方法的调用和GetCustomAttribute扩展方法

Attribute.GetCustomAttribute 方法 在.net文档中我们可以看到有许多的重载
例如:

//应用
    [Defind]
    public class Class1
    {
     
    }
//创建
  public class DefindAttribute : Attribute
    {
        public DefindAttribute()
        {
            Console.WriteLine("特性创建");
        }
    }

//调用
    public class textinvoke
    {
        public void text() {
            Type type1 = typeof(Class1);
            Assembly assembly1 = type1.Assembly;
           // DefindAttribute attribute1 = Attribute.GetCustomAttribute(assembly1, typeof(DefindAttribute)) as DefindAttribute;
             DefindAttribute attribute1 = Attribute.GetCustomAttribute(type1, typeof(DefindAttribute)) as DefindAttribute;
            Console.WriteLine(attribute1);
        }
    }

在我们实现textinvoke类中的text方法时会发现attribute1返回是null,这是因为我们并没有把特性应用到程序集中 ,当我们把GetCustomAttribute中第一个参数换为type时此时能成功调用是因为我们重载了GetCustomAttribute(MemberInfo, Type)这个方法所以我们使用时只需要根据指定需求查找文档调用即可。
除了用Attribute类中的GetCustomAttribute方法获取指定特性以外我们还可以用System.Reflection 中CustomAttributeExtensions类中的GetCustomAttribute扩展方法

扩展方法是什么
文档上扩展方法的解释是 使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种静态方法,但可以像扩展类型上的实例方法一样进行调用。
例如:

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this string str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
-----------------
string s = "Hello Extension Methods";
int i = s.WordCount();
//扩展方法也能正常调用
string s = "Hello Extension Methods";
int i = MyExtensions.WordCount(s);

现在我们再看CustomAttributeExtensions类中的GetCustomAttribute方法
例如public static Attribute? GetCustomAttribute (this System.Reflection.MemberInfo element, Type attributeType);
可以看出这是对Memberinfo的扩展 所以Memberinfo类下所有的子类都能用这个扩展方法
例如:

    [Defind1]
    public class Class1
    {
        [Defind1]
        public void cs(int a)
        {
            Console.WriteLine("反射调用");
        }
    }
//创建
    public class Defind1Attribute : Attribute
    {
        public Defind1Attribute()
        {
            Console.WriteLine("特性创建");
        }
    }
    //调用
    //类上
    Type type2 = typeof(Class1);
    var customAttribute1 = type2.GetCustomAttribute(typeof(Defind1Attribute));
    //方法上
    MethodInfo method = type2.GetMethod("cs");
    var customAttribute2 = method.GetCustomAttribute(typeof(Defind1Attribute));

可以根据自己需要选择对应重载

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值