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

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

运用范围

程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(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. Navi.Soft30.产品.DataWindowNet.操作手册

    1概述 1.1功能简介 Sybase公司的PowerBuilder开发工具,在以前VS工具没有成事以前,是相当风光的.微软都要与其合作,学习它Db方面的技术,才成就了SQLServer数据库.PB开发 ...

  2. Navi.Soft30.产品.格式化.操作手册

    1系统简介 1.1功能简述 在软件开发过程中,我们对字符串操作最多. 尤其是Web开发时,数据交换一般采用JSON或XML.本产品作用是格式化各种常用字符串,目前包括:Json,Xml,Html,Sq ...

  3. android Studio NDK

    官方文档地址: https://developer.android.com/studio/projects/add-native-code.html#download-ndk 最近推出CMake方式集 ...

  4. Centos 6.5 下安装socket5代理

    ---恢复内容开始--- 1. 安装 先安装依赖库 yum -y install gcc gcc-c++ automake make pam-devel openldap-devel cyrus-sa ...

  5. egit - not authorized

    A. To specify credentials individually for each remote Open Git repositories view, open "Remote ...

  6. Android之 -WebView实现离线缓存阅读

    前言 本篇博客要实现的是一个离线下载和离线阅读的功能,这是很多阅读类app都常见的一个功能,典型的应用就是网易新闻.什么是离线下载?其实这个概念是比较模糊,是离线之后下载呢,还是下载之后离线,但稍微有 ...

  7. Unity3d游戏中自定义贝塞尔曲线编辑器[转]

    关于贝塞尔曲线曲线我们再前面的文章提到过<Unity 教程之-在Unity3d中使用贝塞尔曲线>,那么本篇文章我们来深入学习下,并自定义实现贝塞尔曲线编辑器,贝塞尔曲线是最基本的曲线,一般 ...

  8. 天朝专用- 配置pypi镜像

    使用python者,需要经常安装模块,可是身在天朝.pypi.python.org 站点稳定性相当差,为了很更好的使用pip安装模块. 请使用镜像. mac/linux 环境 在用户当前目录下 如没有 ...

  9. wamp2.5 不能运行在win2003的解决方法

    安装时提示 httpd.exe 不是有效的 win32程序 之后就启动不了,连小icon都不显示了 经查发现 wampserver 2.5用 vc11编译,并使用了他的类库 vc11是不支持 xp和 ...

  10. POJ 3320 Jessica's Reading Problem

    Jessica's Reading Problem Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 6001   Accept ...