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

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

运用范围

程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(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. Java socket 多线程编程 示例

    参照网上代码: 1.工程: 2.代码: Client.java package com.my.socket.test; import java.io.BufferedReader; import ja ...

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

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

  3. WPF下载远程文件,并显示进度条和百分比

    WPF下载远程文件,并显示进度条和百分比 1.xaml <ProgressBar HorizontalAlignment="Left" Height="10&quo ...

  4. 移动应用安全开发指南(Android)--完结篇(http://www.bubuko.com/infodetail-577312.html)

    1.认证和授权 概述 认证是用来证明用户身份合法性的过程,授权是用来证明用户可以合法地做哪些事的过程,这两个过程一般是在服务器端执行的,但也有的APP出于性能提升或用户体验等原因,将其做在客户端完成, ...

  5. Oracle存储过程,以逗号分隔字符串传参的处理

    Oracle存储过程,经常会遇见传入的参数是逗号分隔. 处理需要3步: 第一步,创建Type类型 第二部,创建函数 第三部,创建存储过程 代码如下: 第一步: create or replace ty ...

  6. android开发(50) Android透明状态栏。适用于 4.4 以上及 5.0以上设备

    概述 有时候我们想在 andorid 手机上实现一种 跨越 顶部状态栏的效果,比如一张图片直接显示在 状态栏内.比如下图: 这个页面里有张图片,这个图片显示在整个页面的上部分.状态栏是 漂浮在这个图片 ...

  7. 针对 SQL Server 2008 在Windows Server 2008上的访问配置 Windows 防火墙

    现在Windows Server 2008 服务器用的越来越多,2008的防火墙比2003的有了很大的增强,安全性有了更大的提高. 甚至80端口的出站默认都是被关闭的.所以如果在2008Server上 ...

  8. JQM[jquery mobile] 实战经验汇总

    动态装载的子页面(data-role=”page”),完全不用page div之外的tag,也不会起作用.子页面的javascript脚本必须写在page的</div>之前. 切换按钮(a ...

  9. linq join多字段

    from VS in m2db.Inf_VehicleSale join RS1 in m2db.His_RecSale on new { VS.vehicleCode, auctionCode=VS ...

  10. php 连接redis,并登录验证

    环境: centos7 上安装了redis, 同时安装了php的redis扩展 yum install redis yum install php-pecl-redis redis服务端设置了登录密码 ...