引用:https://www.xin3721.com/ArticlecSharp/c11686.html
属性(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()]
public string Name { get; set; } [StringLength()]
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#教程之C#属性(Attribute)用法实例解析的更多相关文章
-
C#属性(Attribute)用法实例解析
属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文就以实例形式分析了C#中属性的应用.具体入戏: 一.运用范围 程序集,模块,类型(类,结构,枚举,接口,委 ...
-
mysql中limit的用法实例解析
mysql中limit的用法解析. 在mysql中,select * from table limit m,n.其中m是指记录开始的index,从0开始,n是指从第m条开始,取n条. 例如: mysq ...
-
python的模块future用法实例解析
计算机的知识太多了,很多东西就是一个使用过程中详细积累的过程.最近遇到了一个很久关于future的问题,踩了坑,这里就做个笔记,免得后续再犯类似错误. future的作用:把下一个新版本的特性导入 ...
-
python中super的用法实例解析
概念 super作为python的内建函数.主要作用如下: 允许我们避免使用基类 跟随多重继承来使用 实例 在单个继承的场景下,一般使用super来调用基类来实现: 下面是一个例子: class Ma ...
-
Pandas高级教程之:GroupBy用法
Pandas高级教程之:GroupBy用法 目录 简介 分割数据 多index get_group dropna groups属性 index的层级 group的遍历 聚合操作 通用聚合方法 同时使用 ...
-
Highmaps网页图表教程之Highmaps第一个实例与图表构成
Highmaps网页图表教程之Highmaps第一个实例与图表构成 Highmaps第一个实例 下面我们来实现本教程的第一个Highmaps实例. [实例1-1:hellomap]下面来制作一个中国地 ...
-
Spring 系列教程之 bean 的加载
Spring 系列教程之 bean 的加载 经过前面的分析,我们终于结束了对 XML 配置文件的解析,接下来将会面临更大的挑战,就是对 bean 加载的探索.bean 加载的功能实现远比 bean 的 ...
-
jQuery中attr()方法用法实例
本文实例讲述了jQuery中attr()方法用法.分享给大家供大家参考.具体分析如下: 此方法设置或返回匹配元素的属性值. attr()方法根据参数的不同,功能也不同. 语法结构一: 获取第一个匹配元 ...
-
Tkinter教程之Message篇
本文转载自:http://blog.csdn.net/jcodeer/article/details/1811326 '''Tkinter教程之Message篇'''#Message也是用来显示文本的 ...
随机推荐
-
ROS主题发布订阅控制真实的机器人下位机
先模拟控制小乌龟 新建cmd_node.ccpp文件: #include"ros/ros.h" #include"geometry_msgs/Twist.h" ...
-
Linux目录介绍
/: 根目录,一般根目录下只存放目录,不要存放文件,/etc./bin./dev./lib./sbin应该和根目录放置在一个分区中/bin:/usr/bin: 可执行二进制文件的目录,如常用的命令ls ...
-
bzoj 1057: [ZJOI2007]棋盘制作 单调栈
题目链接 1057: [ZJOI2007]棋盘制作 Time Limit: 20 Sec Memory Limit: 162 MBSubmit: 2027 Solved: 1019[Submit] ...
-
Redis源代码分析(二十八)--- object创建和释放redisObject物
今天的学习更有效率.该Rio分析过,学习之间的另一种方式RedisObject文件,只想说RedisObject有些生成和转换.都是很类似的.列出里面长长的API列表: /* ------------ ...
-
Django进阶使用
Model 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MySQLdb 来连接数据库,并编写数据访问层代码 业务逻辑层去调用数据访问层执行 ...
-
9.6Django
2018-9-6 12:56:32 2018-9-6 18:32:22 把那个用户列表的页面优化了一下!用了老师更好看的页面,但是功能还是那些! 就是修改一下url就好! 放在我我的github : ...
-
BZOJ3157/BZOJ3516 国王奇遇记(矩阵快速幂/数学)
由二项式定理,(m+1)k=ΣC(k,i)*mi.由此可以构造矩阵转移,将mi*ik全部塞进去即可,系数即为组合数*m.复杂度O(m3logn),因为大常数喜闻乐见的T掉了. #include< ...
-
ballerina 学习十三 函数&;&;documentation
ballerina 函数和其他语言一样的,可以实现重用 简单例子 代码 import ballerina/io; documentation { `User` is a user defined ob ...
-
Firebird execute block 批处理
火鸟的批处理,效率好高,使用简单. execute block as declare variable i ; begin ) do begin :i = :i + ; insert into m_u ...
-
[Scala]Scala学习笔记一 基础
1. 变量 val定义的值实际上是一个常亮,无法改变其内容 scala> val num = 0 num: Int = 0 scala> num = 2 <console>:1 ...