定制特性

1,定制特性

①C#允许用一个前缀明确指定特性要应用的目标元素

[assembly: AssemblyVersion("1.0.0.0")]

②AttributeUsage. Inherited(特性应用于基类时,是否同时应用于派生类和重写的方法)

    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,Inherited = true)]
    internal class TastyAttribute : Attribute
    {
    }

    [Tasty,Serializable]
    internal class BaseType
    {
        [Tasty]
        protected virtual void DoSomething(){}
    }
    //继承父类Tasty的特性
    internal class DerivedType : BaseType
    {
        //继承Tasty的特性
        protected override void DoSomething(){}
    }
    //如果特性类没有显示的引用AttributeUsage,则默认AttributeUsage如下
    [AttributeUsage(AttributeTargets.All,AllowMultiple = false, Inherited = true)]

 2,检测定制特性

方法名称

说明

IsDefined

至少有一个指定的Attribute派生类的实例与目标关联,就会返回true。

这个方法的效率很高,它不会构造(反序列化)特性类的任何实例

GetCustomerAttributes

返回应用于目标的指定特性对象的集合。

每个实例都使用编译时指定的参数、字段和属性来构造(反序列化)。

没有指定的集合则返回空集合。

GetCustomerAttribute

返回应用于目标的指定特性对象的实例。

实例使用编译时指定的参数、字段和属性来构造(但序列化)。

没有指定的特性实例,则返回null。

目标指定了多个实例,则抛出异常

3,检查定制特性时不创建从Attribute派生的对象

调用Attribute的GetCustomAttribute或者GetCustomerAttribute方法时,这些方法会在内部调用特性类的构造器,而且可能调用属性的set访问器方法。可能存在安全隐患

            //在查找特性的同时禁止执行特性类中的代码
            CustomAttributeData.GetCustomAttributes()
学习永不止境,技术成就梦想。
原文地址:https://www.cnblogs.com/zd1994/p/7044203.html