c#特性简述使用

一自定义特性

我们主要讲一下如何自定义特性,定义的方式和普通的类定义方式一致,但是,
第一:需要继承标准特性类
第二:需要添加标准特性,用来限制特性的使用范围等

第三:必须要定义构造函数,即使是空的

第四:当有参构造时,必须要有空构造

如下:


[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]

    public class FirstSayAttribute: Attribute
    {
        public FirstSayAttribute() {  }
        public FirstSayAttribute(string name, int sore,string message) { this.name = name; this.sore = sore; this.message = message; }
        public string name { get; set; }
        public int sore { get; set; }
        public string message { get; set; }

    }

二测试类

[FirstSayAttribute(name = "dj", sore = 100, message = "222")]
    [FirstSayAttribute(name = "sq", sore = 100, message = "666")]
    public class Test
    {
    }

三执行

 class Program
    {
        static void Main(string[] args)
        {


            System.Reflection.MemberInfo info = typeof(Test);
            FirstSayAttribute[] customAttrLsit = Attribute.GetCustomAttributes(info, typeof(FirstSayAttribute)) as FirstSayAttribute[];
            for (int i = 0; i < customAttrLsit.Length; i++)
            {
                Console.WriteLine("================================================");
                Console.WriteLine("创建人:{0}", customAttrLsit[i].name);
                Console.WriteLine("创建时间:{0}", customAttrLsit[i].sore);
                Console.WriteLine("备注消息:{0}", customAttrLsit[i].message);
            }
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值