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

2023-11-18

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);
            }
        }
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C#自定义一个简单的特性Attribute 的相关文章