C# 特性的使用

特性的用处

特性可以向程序中添加元数据(数据的数据:对数据进行解析的数据)

特性的使用

特性可以通过反射技术 进行获取 处理

特性的创建

自定义特性 需要继承Attribute类 类名后缀可带Attribute 不带也可以

 public  class AuthorAttribute:Attribute
    {
        private string name;
        public double version;

        public AuthorAttribute(string name, double version =1.0)
        {
            this.name = name;
            this.version = version;
        }
    }

AttributeUsage

控制自定义特性的使用,有两个构造函数

AttributeUsageAttribute(AttributeTargets validOn) 

//AllowMultiple  是否可以多次使用
//inherited  继承类是否可以继承此特性
AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, inherited)


//AttributeTargets 枚举
public enum AttributeTargets
{
   
    Assembly = 0x1,
    Module = 0x2,
    Class = 0x4,
    Struct = 0x8,
    Enum = 0x10,
    Constructor = 0x20,
    Method = 0x40,
    Property = 0x80,
    Field = 0x100,
    Event = 0x200,
    Interface = 0x400,
    Parameter = 0x800,
    Delegate = 0x1000,
    ReturnValue = 0x2000,
    GenericParameter = 0x4000,
    All = 0x7FFF
}

反射中的使用

[Author("P. Ackerman", version = 1.1)]
class SampleClass

//在概念上等效于:
Author anonymousAuthorObject = new Author("P. Ackerman");
anonymousAuthorObject.version = 1.1;

当 查询 SampleClass 来获取特性后才会执行以上代码

SampleClass 调用 GetCustomAttributes 会导致按上述方式构造并初始化一个 Author 对象。如果该类具有其他特性,则按相似的方式构造其他特性对象。

GetCustomAttributes 返回 Author 对象和数组中的任何其他特性对象。之后就可以对此数组进行迭代,确定根据每个数组元素的类型所应用的特性,并从特性对象中提取信息。

 [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,AllowMultiple =true,Inherited =false)]
public  class Author:Attribute
{
    private string name;
    public double version;

    public Author(string name, double version =1.0)
    {
        this.name = name;
        this.version = version;
    }
    public string GetName()
    {
        return this.name;
    }
}

 class Program
    {
        static void Main(string[] args)
        {
            PrintAuthorInfo(typeof(IndiaBook));
            Console.ReadKey();
        }
        private static void PrintAuthorInfo(Type t)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(t);
            foreach(var attr in attrs)
            {
                if(attr is Author)
                {
                    Author a = (Author)attr;
                    Console.WriteLine("{0},version{1}",a.GetName(),a.version);
                }
            }
        }
    }
    [Author("EnglishBook001", 1.0)]
    public class EnglishBook
    {

    }
    [Author("ChineseBook001",2.0)]
    public class ChineseBook
    {

    }

    [Author("india",1.0),Author("india002",2.0)]
    public class IndiaBook: ChineseBook
    {
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值