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

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

运用范围

程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(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#】属性(Attribute)的更多相关文章

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

    属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文就以实例形式分析了C#中属性的应用.具体入戏: 一.运用范围 程序集,模块,类型(类,结构,枚举,接口,委 ...

  2. Android应用资源--之属性(Attribute)资源

    原文链接: http://wujiandong.iteye.com/blog/1184921 属性(Attribute)资源:属于整个Android应用资源的一部分.其实就是网上一堆介绍怎么给自定义V ...

  3. opencart3属性attribute实现换行等简单html代码

    opencart3属性attribute在前台页面默认是没有解析html代码功能的,比如想实现换行,后台这样写:line 1<br>line 2,但前台产品页也是line 1<br& ...

  4. Servlet中的属性(attribute)和参数(parameter)的区别

    1.引子 初学者对属性(attribute)和参数(parameter)容易搞混.没搞清他们的区别,项目中就可能出现一此莫名其妙的问题. 2.两者的区别 1) 属性(attribute) 属性是在后台 ...

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

    引用:https://www.xin3721.com/ArticlecSharp/c11686.html 属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文 ...

  6. 属性 Attribute

    一.创建属性 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor, AllowMultiple = true, ...

  7. 转发和重定向简介及与之相关的(URL)参数(parameter)、属性(attribute)问题探讨

    1.引子 转发和重定向是我们在做web项目中常用到的两个术语,有必要理清两者的区别和与之相关的参数.属性获取问题. 2.转发和重定向 1).转发 转发是服务器行为,将当前请求(Request)和响应( ...

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

    boolean attribute(布尔值属性) boolean attribute     HTML - Why boolean attributes do not have boolean val ...

  9. 属性attribute和property的区别

    <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content ...

  10. 蓝牙BLE: ATT协议层中属性(Attribute)

    ATT(Attribute Protocol)属性层是GATT和GAP的基础,它定义了BLE协议栈上层的数据结构和组织方式. 属性(Attribute)概念是ATT层的核心,ATT层定义了属性的内容, ...

随机推荐

  1. puma vs passenger vs rainbows! vs unicorn vs thin 适用场景 及 performance

    ruby的几个web server,按照开发活跃度.并发方案及要点.适用场景等分析puma vs passenger vs rainbows! vs unicorn vs thin. 1. thin: ...

  2. HashSet HashTable HashMap的区别 及其Java集合介绍

    (1)HashSet是set的一个实现类,hashMap是Map的一个实现类,同时hashMap是hashTable的替代品(为什么后面会讲到). (2)HashSet以对象作为元素,而HashMap ...

  3. 修改 Semantic UI 的默认字体

    Semantic UI 默认使用的是谷歌提供的字体,并且是直接使用了谷歌的官方链接.由于大家都知道的原因,谷歌网站在国内访问速度很差,甚至根本无法访问,还有就是可能会在离线环境下使用 Semantic ...

  4. RxJava操作符之Share, Publish, Refcount

    原文链接:http://nerds.weddingpartyapp.com/tech/2015/01/21/rxjava-share-publish-refcount-and-all-that-jaz ...

  5. MySQL HA方案之MySQL半复制+MHA+Keepalived+Atlas+LVS[转]

    MySQL HA方案之MySQL半复制+MHA+Keepalived+Atlas+LVS 简介 目前Mysql高可用的方案有好多,比如MMM,heartbeat+drbd,Cluster等,还有per ...

  6. (笔记)Linux内核学习(八)之定时器和时间管理

    一 内核中的时间观念 内核在硬件的帮助下计算和管理时间.硬件为内核提供一个系统定时器用以计算流逝的时间.系 统定时器以某种频率自行触发,产生时钟中断,进入内核时钟中断处理程序中进行处理. 墙上时间和系 ...

  7. 使用NSKeyedArchiver归档

    将各种类型的对象存储到文件中,而不仅仅是字符串.数组和字典类型,有一种更灵活的方法.就是利用NSKeyedAarchiver类创建带键(keyed)的档案来完成. Mac OS X从版本10.2开始支 ...

  8. coreData 深入理解4 --总结 (线程安全与同步--iOS5 前后对比)

    Core Data是iOS中很重要的一个部分,可以理解为基于SQLite(当然也可以是其他的Storage,如In-memory,只是SQLite比较常见)的一个ORM实现,所以有关系数据库的特性,又 ...

  9. POJ 1012 Joseph

    Joseph Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 44650   Accepted: 16837 Descript ...

  10. 由于无法创建应用程序域,因此未能执行请求。错误: 0x80070002 系统找不到指定的文件

    前两天安装了一堆补丁后突然发现,原本正常使用了一年的应用系统打不开了,到事件日志中发现有.net framewok 2.0的补丁安装失败的日志,于从从重装补丁开始.到重新注册.net框架,再到所有.n ...