编写自定义特性

来源:互联网 发布:淘宝与客服聊天图片 编辑:程序博客网 时间:2024/05/22 07:52

自定义特性一般标注在作用的程序元素的上方

编译器首先组合特性名称和Attribute,然后寻找该组合名,所以特性名为FieldName和FieldNameAttribute的两个特性没有区别

编译器将寻找包含有这个名称的类,它直接或者间接的派生资System.Attribute


编写自定义类的步骤:

1.指定AttributeUsage特性,这个特性用在其他特性上,它有以下三个参数

AttributeTargets枚举指定特性的应用程序元素类型,如果是应用于程序集或者模块,特性可以放在代码的任何地方,格式如下:

[assembly:SomeAssemblyAttribute(Params)][module:SomeAssemblyAttribute(Params)]

AllowMultiple = true; 说明特性可以对同一对象使用多次

Inherited = true;说明应用到类和接口上的特性自动添加到派生类和接口上


2.指定特性的参数和可选参数,分别用了两种语法,

第一种 [FieldName("hxx")] 则自定义特性中应该写一个匹配类型的构造函数

第二种[FieldName("sy", Comment = "the most wonderful girl in the world")] 那么定义的时候最好包含这个字段 public string Comment { get; set; }


3.demo

using System;namespace WhatsNewAttributes{    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,        AllowMultiple = true,Inherited = false)]    public class LastModifiedAttribute: Attribute    {        private readonly DateTime _dateModified;        private readonly string _changes;        public LastModifiedAttribute(string dateModified,string changes)        {            _dateModified = DateTime.Parse(dateModified);            _changes = changes;        }        public DateTime DateModified => _dateModified;        public string Changes => _changes;        public string issues { set; get; }    }    [AttributeUsage(AttributeTargets.Assembly)]    public class SupportWhatsNewAttributes : Attribute    {    }}