C#自定义一个简单的特性Attribute

C#自定义一个简单的特性Attribute

首先我们自定义一个类,这个类继承Attribute,命名为MyAttribute(注意:要以Attribute结尾),然后在类中随便设置了一个属性,名叫Message,还创建了一个构造函数,这样一个简单的特性类就创建好了。

public class MyAttribute : Attribute
{
    public string Message { get; set; }
    public MyAttribute(string message)
    {
        Message = message;
    }
}

之后我们再创建一个类加上我们自定义的特性
这里的[My(“haha”)]就表明给Test类加上了MyAttribute的一个实例,这个实例的Message属性赋值成了"haha"

[My("haha")]
class Test
{

}

然后我们就可以在Main函数中测试一下,看看我们的特性有没有生效

class Program
{
    static void Main(string[] args)
    {
        Type testType = typeof(Test);
        if (testType.IsDefined(typeof(MyAttribute), true))
        {
            MyAttribute myAttribute = (MyAttribute)testType.GetCustomAttribute(typeof(MyAttribute));
            Console.WriteLine(myAttribute.Message);
        }
    }
}

不出意外的话主函数在运行后会输出haha

完整代码是这样的

using System;
using System.Reflection;

namespace helloAttribute
{
    public class MyAttribute : Attribute
    {
        public string Message { get; set; }
        public MyAttribute(string message)
        {
            Message = message;
        }
    }

    [My("haha")]
    class Test
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
            Type testType = typeof(Test);
            if (testType.IsDefined(typeof(MyAttribute), true))
            {
                MyAttribute myAttribute = (MyAttribute)testType.GetCustomAttribute(typeof(MyAttribute));
                Console.WriteLine(myAttribute.Message);
            }
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值