【C#】属性(Attribute)

如果程序员是猫,你是哪只猫?

这个是我一直都很喜欢的一个技术,不是很麻烦,也不是很难理解,和反射配合起来,只有你想不到没有做不到的用途(夸张了哈)。

运用范围

程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attribute

  

 [AttributeUsage(AttributeTargets.All)]
    public class TestAttribute : Attribute
    {
    }
    [TestAttribute]//结构
    public struct TestStruct { }

    [TestAttribute]//枚举
    public enum TestEnum { }

    [TestAttribute]//类上
    public class TestClass
    {
        [TestAttribute]
        public TestClass() { }

        [TestAttribute]//字段
        private string _testField;

        [TestAttribute]//属性
        public string TestProperty { get; set; }

        [TestAttribute]//方法上
        [return: TestAttribute]//定义返回值的写法
        public string TestMethod([TestAttribute] string testParam)//参数上
        {
            throw new NotImplementedException();
        }
    }

这里我们给出了除了程序集和模块以外的常用的Atrribute的定义。

自定义Attribute

为了符合“公共语言规范(CLS)”的要求,所有的自定义的Attribute都必须继承System.Attribute。

第一步:自定义一个检查字符串长度的Attribute

    [AttributeUsage(AttributeTargets.Property)]
    public class StringLengthAttribute : Attribute
    {
        private int _maximumLength;
        public StringLengthAttribute(int maximumLength)
        {
            _maximumLength = maximumLength;
        }

        public int MaximumLength
        {
            get { return _maximumLength; }
        }
    }

AttributeUsage这个系统提供的一个Attribute,作用来限定自定义的Attribute作用域,这里我们只允许这个Attribute运用在Property上,内建一个带参的构造器,让外部传入要求的最大长度。

第二步:创建一个实体类来运行我们自定义的属性

 public class People
    {
        [StringLength(8)]
        public string Name { get; set; }

        [StringLength(15)]
        public string Description { get; set; }
    }

定义了两个字符串字段Name和Description, Name要求最大长度为8个,Description要求最大长度为15.

第三步:创建验证的类

 public class ValidationModel
    {

        public void Validate(object obj)
        {
            var t = obj.GetType();

            //由于我们只在Property设置了Attibute,所以先获取Property
            var properties = t.GetProperties();
            foreach (var property in properties)
            {

                //这里只做一个stringlength的验证,这里如果要做很多验证,需要好好设计一下,千万不要用if elseif去链接
                //会非常难于维护,类似这样的开源项目很多,有兴趣可以去看源码。
                if (!property.IsDefined(typeof(StringLengthAttribute), false)) continue;

                var attributes = property.GetCustomAttributes();
                foreach (var attribute in attributes)
                {
                    //这里的MaximumLength 最好用常量去做
                    var maxinumLength = (int)attribute.GetType().
                        GetProperty("MaximumLength").
                        GetValue(attribute);

                    //获取属性的值
                    var propertyValue = property.GetValue(obj) as string;
                    if (propertyValue == null)
                        throw new Exception("exception info");//这里可以自定义,也可以用具体系统异常类

                    if (propertyValue.Length > maxinumLength)
                        throw new Exception(string.Format("属性{0}的值{1}的长度超过了{2}", property.Name, propertyValue, maxinumLength));
                }
            }

        }
    }

这里用到了反射,因为Attribute一般都会和反射一起使用,这里验证了字符串长度是否超过所要求的,如果超过了则会抛出异常

   private static void Main(string[] args)
        {

            var people = new People()
            {
                Name = "qweasdzxcasdqweasdzxc",
                Description = "description"
            };

            try
            {
                new ValidationModel().Validate(people);
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();

        }

基础篇不涉及很多高级用法,这个明白以后,变化可以很多。

【C#】属性(Attribute)

时间: 2024-08-25 01:55:06

【C#】属性(Attribute)的相关文章

Android应用资源系列之属性(Attribute)资源

转自:http://wujiandong.iteye.com/blog/1184921 Android anroidAttribute自定义组件属性 属性(Attribute)资源:属于整个Android应用资源的一部分.其实就是网上一堆介绍怎么给自定义View添加自己的属性文章里的attrs文件,此文件位于../res/values/目录下 当别人通过XML文件配置的方式来创建你开发的自定义组件,并且还能动态设置你自定义组件的属性时,这时候你就需要给你自己自定义的组件配上一个XML属性资源文件

C#属性(Attribute)用法实例解析

属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文就以实例形式分析了C#中属性的应用.具体入戏: 一.运用范围 程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attribute [AttributeUsage(AttributeTargets.All)] public class TestAttribute : Attribute { } [TestAttribute]//结构

C#教程之C#属性(Attribute)用法实例解析

引用:https://www.xin3721.com/ArticlecSharp/c11686.html 属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文就以实例形式分析了C#中属性的应用.具体入戏: 一.运用范围 程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attribute [AttributeUsage(AttributeTargets.All)] public cl

boolean attribute(布尔值属性) attribute vs property

boolean attribute(布尔值属性) boolean attribute     HTML - Why boolean attributes do not have boolean value?     Boolean HTML Attributes   HTML Boolean Attributes A number of attributes are boolean attributes. The presence of a boolean attribute on an ele

iOS中属性及其特质@property、attribute

属性: 属性@property和属性attribute不同,@property在OC里有自己的一套专对实例变量的处理机制.attribute我们可以特指属性所具有或遵循的特质. 使用属性,编译器就会自动编写访问这些属性所需的方法,此过程叫做“自动合成”(autosynthesis).自动合成的过程是编译器在编译期执行.除此之外,编译器还要自定向类中添加适当类型的实例变量,并且在属性名前面加下划线,以此作为实例变量的名字.也可以用@synthesize 类指定实例变量的名字: 如:用@proper

浅析C#中的Attribute

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

EL属性范围用法sessionScope等(转)

EL 全名为Expression Language EL 语法很简单,它最大的特点就是使用上很方便.接下来介绍EL主要的语法结构: ${sessionScope.user.sex} 所有EL都是以${为起始.以}为结尾的.上述EL范例的意思是:从Session的范围中,取得 用户的性别.假若依照之前JSP Scriptlet的写法如下: User user = (User)session.getAttribute("user"); String sex = user.getSex( )

jquery中常用的节点查找,属性过滤

注意:[selector]表示可加的过滤节点 jQuery.parent([selector]) 找父亲节点,可以传入selector进行过滤,比如$("span").parent()或者$("span").parent(".class") jQuery.parents(selector),类似于jQuery.parents(selector),但是是查找所有祖先元素,不限于父元素 jQuery.children([selector]).返回所有

JAVAWEB开发之JSTL标签库的使用、 自己定义EL函数、自己定义标签(带属性的、带标签体的)

JSTL JSTL简单介绍: JSTL的全称:JSP Standard Tag Library.JSP标准标签库 JSTL的作用: 提供给Java Web开发者一个标准通用的标签函数库 和EL来代替传统直接在页面上嵌入Java程序(Scripting)的做法,以提高程序可读性.维护性和方便性 JSTL的版本号: JSTL的主要版本号是1.0.1.1和1.2(差别不大) 1.0版本号EL表达式还没有纳入官方规范 1.1和1.2版本号EL表达式已经纳入了官方规范 JSTL1.1 下载对应的jar包

libxml的使用(2)--读取节点属性

在上一篇文章当中,我读取了各个节点的名字和内容,现在我将读取各个节点的属性. [html] view plaincopyprint? <?xml version="1.0" encoding="UTF-8"?> <root> <node1>content1</node1> <node2 attribute="yes">content2</node2> <node3>