C#属性(Attribute)用法实例解析
属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变。本文就以实例形式分析了C#中属性的应用。具体入戏:
一、运用范围
程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(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,所以先获取Propertyvar 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(); }
转载于:https://www.cnblogs.com/rinack/p/4260200.html
C#属性(Attribute)用法实例解析相关推荐
- python画猴子_Python猴子补丁Monkey Patch用法实例解析
属性在运行时的动态替换,叫做猴子补丁(Monkey Patch). 为什么叫猴子补丁 属性的运行时替换和猴子也没什么关系,关于猴子补丁的由来网上查到两种说法: 1.这个词原来为Guerrilla Pa ...
- html margin属性,HTML5属性:margin属性的用法实例
这篇文章给大家介绍的内容是关于HTML5属性:margin属性的用法实例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. Document p{ width: 100px; heigh ...
- python中enumerate在for循环中用法_python中enumerate的用法实例解析
在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法.具体如下: enumerate参数为可遍历的变量,如 字符串,列 ...
- python enumerate_python中enumerate的用法实例解析
在python中enumerate的用法多用于在for循环中得到计数,本文即以实例形式向大家展现python中enumerate的用法.具体如下: enumerate参数为可遍历的变量,如 字符串,列 ...
- python猴子补丁_Python猴子补丁Monkey Patch用法实例解析
属性在运行时的动态替换,叫做猴子补丁(Monkey Patch). 为什么叫猴子补丁 属性的运行时替换和猴子也没什么关系,关于猴子补丁的由来网上查到两种说法: 1.这个词原来为Guerrilla Pa ...
- Nodejs 文件 与 路径 相关用法实例解析
Nodejs 文件 与 路径 相关用法 CSDN用户名:jcLee95 邮箱:291148484@163.com 原创不易,感谢点赞支持. 1.路径 (1)引入path模块 const path = ...
- Python单元测试及unittest框架用法实例解析
例题取用登录模块:代码如下 def login_check(username,password):''' 登录校验的函数:param username:账号:param password: 密码:re ...
- Java的clone()用法实例解析
1.背景 用java写程序的时候很苦恼的一件事就是,如果将一个对象a赋给另一个对象b,那么你改变a的变量值得时候,b的值也对应的变化.如果我们只想单纯的获取那个时刻的a的状况给b的话,就要用到clon ...
- python中super的用法实例解析
概念 super作为python的内建函数.主要作用如下: 允许我们避免使用基类 跟随多重继承来使用 实例 在单个继承的场景下,一般使用super来调用基类来实现: 下面是一个例子: class Ma ...
- android theme 使用方法,Android入门之Style与Theme用法实例解析
就目前的互联网发展来看,已经有越来越多互联网企业都在Android平台上部署其客户端,并且为了提升用户体验,这些客户端都做得布局合理而且美观.本文所要介绍的Android的Style设计就是提升用户体 ...
最新文章
- Reverse Engineering Custom DataTypes - GUID() in SQL Server to PostgreSQL
- python装饰器函数-python3 函数:函数装饰器
- doxygen相关问题 转
- 把Eclipse项目转换成Maven项目
- java监控数据库的增量_【安德鲁斯】基于脚本的数据库quot;增量更新quot;,如果不改变,每次更新java代码、!...
- HDU 2243 考研路茫茫——单词情结 求长度小于等于L的通路总数的方法
- TCP/UDP相关知识
- HT for Web的HTML5树组件延迟加载技术实现
- python深度学习——手写字符识别
- WIN7 X64完美卸载SQL2008 R2并重装SQL2008
- VS软件设置中的宏定义
- 申请软件著作权有哪些好处,你知道吗?
- php 输入经纬度查询位置,根据经纬度查询附近地点信息
- 高冷一字id_lol高冷而有诗意的id
- python运用maya_适用于maya和其他3d应用程序的python版本
- Element-UI 上传图片到达一定数量后隐藏图片上传按钮
- 只知道wxid怎么添加好友
- 来吧!带你玩转 Excel VBA
- 开发会自测为什么测试还会单独存在?软件测试八大误区
- 从零开始创建一个uni-app项目