一、自定义特性与使用

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。

特性的定义与使用

1.创建一个自定义特性类

    /// <summary>
    /// 此处有特性可放置的使用限制,此刻只列举属性和Filed
    /// 类名后缀必须以Attribute结尾
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class UpAttribute : Attribute
    {
        public bool Need { get; set; }
    }

 2.定义一个需要使用特性的类

    public class Info
    {
        // 列举的是属性,若使用Filed,移除{get;set;}
        public string msg1 { get; set; }
        [Up(Need = false)]
        public string msg2 { get; set; }
        [Up(Need = true)]
        public string msg3 { get; set; }

        public Info(string a, string b, string c)
        {
            msg1 = a;
            msg2 = b;
            msg3 = c;
        }
    }

3.具体调用

        static void Main(string[] args)
        {
            var info = new Info("aaaa", "bbbbb", "ccccc");
            //特性通常配合反射使用,因为特性类型只有在对应的Type中的自定义属性中才能获取
            foreach (var item in typeof(Info).GetProperties())
            {
                //此处使用Get方法获取比使用属性的优点在于可以直接将其实例化为对应特定类,方便获取其内部属性
                if (item.GetCustomAttributes(true).Any(it => it is UpAttribute && (it as UpAttribute).Need))
                {
                    Console.WriteLine(item.GetValue(info).ToString().ToUpper());
                }
                else
                {
                    Console.WriteLine(item.GetValue(info).ToString());
                }
            }

            Console.ReadKey();
        }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值