C#中的Attribute简单使用

C#的特性是4.0 才出来的,在什么地方看到最多呢,就是实体类的字段上面,形式是
[类名(参数)]。那么,,
一,什么是特性
特性也是一种对象,关键字是 Attribute,特殊之处在于其编译时就存在了,也就是在程序运行之前就存在了。

二,是用特性的类必须继承 Attribute
先给段简单代码玩一下


        public class student
        {
            [ColumnAttribute("Uname")]  //这里就是调用了,去掉中括号,实际就是构造函数调用
            public string Name { get; set; }
        }
 
        public class ColumnAttribute : Attribute  
        {
            public string Name { get; private set; }
            
            public ColumnAttribute(string name)
            {
                this.Name = name;
            }
        }

那么通过 [ColumnAttribute(“Uname”)] 传递的值如果获取到呢


ColumnAttribute[] Attrs = (ColumnAttribute[])typeof(student).GetCustomAttributes(typeof(ColumnAttribute), true);

foreach (var item in Attrs)
 {
      richTextBox1.AppendText("名称是:" + item.Name + "\n");
}

这样操作就可以了!还可以对字段增加验证,判断,自定义特性等!

猜你喜欢

转载自blog.csdn.net/weixin_42780928/article/details/91811803