C#属性(Attribute)用法实例解析
属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变。本文就以实例形式分析了C#中属性的应用。具体入戏:
一、运用范围
程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(property),Attribute
[AttributeUsage(AttributeTargets.All)] publicclassTestAttribute:Attribute { } [TestAttribute]//结构 publicstructTestStruct{} [TestAttribute]//枚举 publicenumTestEnum{} [TestAttribute]//类上 publicclassTestClass { [TestAttribute] publicTestClass(){} [TestAttribute]//字段 privatestring_testField; [TestAttribute]//属性 publicstringTestProperty{get;set;} [TestAttribute]//方法上 [return:TestAttribute]//定义返回值的写法 publicstringTestMethod([TestAttribute]stringtestParam)//参数上 { thrownewNotImplementedException(); } }
这里我们给出了除了程序集和模块以外的常用的Atrribute的定义。
二、自定义Attribute
为了符合“公共语言规范(CLS)”的要求,所有的自定义的Attribute都必须继承System.Attribute。
第一步:自定义一个检查字符串长度的Attribute
[AttributeUsage(AttributeTargets.Property)] publicclassStringLengthAttribute:Attribute { privateint_maximumLength; publicStringLengthAttribute(intmaximumLength) { _maximumLength=maximumLength; } publicintMaximumLength { get{return_maximumLength;} } }
AttributeUsage这个系统提供的一个Attribute,作用来限定自定义的Attribute作用域,这里我们只允许这个Attribute运用在Property上,内建一个带参的构造器,让外部传入要求的最大长度。
第二步:创建一个实体类来运行我们自定义的属性
publicclassPeople { [StringLength(8)] publicstringName{get;set;} [StringLength(15)] publicstringDescription{get;set;} }
定义了两个字符串字段Name和Description,Name要求最大长度为8个,Description要求最大长度为15.
第三步:创建验证的类
publicclassValidationModel { publicvoidValidate(objectobj) { vart=obj.GetType(); //由于我们只在Property设置了Attibute,所以先获取Property varproperties=t.GetProperties(); foreach(varpropertyinproperties) { //这里只做一个stringlength的验证,这里如果要做很多验证,需要好好设计一下,千万不要用ifelseif去链接 //会非常难于维护,类似这样的开源项目很多,有兴趣可以去看源码。 if(!property.IsDefined(typeof(StringLengthAttribute),false))continue; varattributes=property.GetCustomAttributes(); foreach(varattributeinattributes) { //这里的MaximumLength最好用常量去做 varmaxinumLength=(int)attribute.GetType(). GetProperty("MaximumLength"). GetValue(attribute); //获取属性的值 varpropertyValue=property.GetValue(obj)asstring; if(propertyValue==null) thrownewException("exceptioninfo");//这里可以自定义,也可以用具体系统异常类 if(propertyValue.Length>maxinumLength) thrownewException(string.Format("属性{0}的值{1}的长度超过了{2}",property.Name,propertyValue,maxinumLength)); } } } }
这里用到了反射,因为Attribute一般都会和反射一起使用,这里验证了字符串长度是否超过所要求的,如果超过了则会抛出异常
privatestaticvoidMain(string[]args) { varpeople=newPeople() { Name="qweasdzxcasdqweasdzxc", Description="description" }; try { newValidationModel().Validate(people); } catch(Exceptionex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
希望本文所述实例对大家的C#程序设计能有一定的帮助作用。