C#:自定义特性

0.

先看看什么是特性?

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。
您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。.Net 框架提供了两种类型的特性:预定义特性和自定义特性。

学习网址: http://www.runoob.com/csharp/csharp-attribute.html

预定义特性有: AttributeUsage   Conditional   Obsolete    具体用法看上面的网址

1.

而我们如果想要自定一个特性,就需要创建一个类 继承 Attribute,然后在这个类上面添加 AttributeUsage 声明标签,即可。

如下:

创建自定义特性 DebugInfo:

我们的 DeBugInfo 类将带有三个用于存储前三个信息的私有属性(property)和一个用于存储消息的公有属性(property)。所以 bug 编号、开发人员名字和审查日期将是 DeBugInfo 类的必需的定位( positional)参数,消息将是一个可选的命名(named)参数。

每个特性必须至少有一个构造函数。必需的定位( positional)参数应通过构造函数传递。

[AttributeUsage(AttributeTargets.All,AllowMultiple =true)]
    public class DebugInfo : Attribute {
        private int bugno;
        private String developer;
        private String lastTime;
        public String message;

        public DebugInfo(int bugno, string developer, string lastTime) {
            this.bugno = bugno;
            this.developer = developer;
            this.lastTime = lastTime;
        }

        public int BUGNO {
            get {
                return bugno;
            }
        }
        public String DEVELOPER {
            get {
                return developer;
            }
        }
        public String LASTTIME {
            get {
                return lastTime;
            }
        }
        public String MESSAGE {
            get {
                return message;
            }
            set {
                message = value;
            }
        }

    }

使用如下:

        [DebugInfo(2019,"LiuYan","1/17",message ="这是print方法")]
        public void MyPrint() {
            richTextBox1.AppendText("\r\n123");
        }

利用反射获得自定义特性中的变量:

            Type t = typeof(Myprint方法所在的类);
            var method = t.GetMethod("MyPrint");
            DebugInfo ats = (DebugInfo)method.GetCustomAttribute(typeof(DebugInfo),true);
            int bugNo = ats.BUGNO;
            String name = ats.DEVELOPER;
            String time = ats.LASTTIME;
            String message = ats.message;
            richTextBox1.AppendText("\r\n"+bugNo+" "+name+" "+time+" "+message);

//2019 LiuYan 1/17 1234

完!

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/86517849