【C#】属性(Attribute)
如果程序员是猫,你是哪只猫?
这个是我一直都很喜欢的一个技术,不是很麻烦,也不是很难理解,和反射配合起来,只有你想不到没有做不到的用途(夸张了哈)。
运用范围
程序集,模块,类型(类,结构,枚举,接口,委托),字段,方法(含构造),方法,参数,方法返回值,属性(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)的更多相关文章
- C#属性(Attribute)用法实例解析
属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文就以实例形式分析了C#中属性的应用.具体入戏: 一.运用范围 程序集,模块,类型(类,结构,枚举,接口,委 ...
- Android应用资源--之属性(Attribute)资源
原文链接: http://wujiandong.iteye.com/blog/1184921 属性(Attribute)资源:属于整个Android应用资源的一部分.其实就是网上一堆介绍怎么给自定义V ...
- opencart3属性attribute实现换行等简单html代码
opencart3属性attribute在前台页面默认是没有解析html代码功能的,比如想实现换行,后台这样写:line 1<br>line 2,但前台产品页也是line 1<br& ...
- Servlet中的属性(attribute)和参数(parameter)的区别
1.引子 初学者对属性(attribute)和参数(parameter)容易搞混.没搞清他们的区别,项目中就可能出现一此莫名其妙的问题. 2.两者的区别 1) 属性(attribute) 属性是在后台 ...
- C#教程之C#属性(Attribute)用法实例解析
引用:https://www.xin3721.com/ArticlecSharp/c11686.html 属性(Attribute)是C#程序设计中非常重要的一个技术,应用范围广泛,用法灵活多变.本文 ...
- 属性 Attribute
一.创建属性 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor, AllowMultiple = true, ...
- 转发和重定向简介及与之相关的(URL)参数(parameter)、属性(attribute)问题探讨
1.引子 转发和重定向是我们在做web项目中常用到的两个术语,有必要理清两者的区别和与之相关的参数.属性获取问题. 2.转发和重定向 1).转发 转发是服务器行为,将当前请求(Request)和响应( ...
- boolean attribute(布尔值属性) attribute vs property
boolean attribute(布尔值属性) boolean attribute HTML - Why boolean attributes do not have boolean val ...
- 属性attribute和property的区别
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content ...
- 蓝牙BLE: ATT协议层中属性(Attribute)
ATT(Attribute Protocol)属性层是GATT和GAP的基础,它定义了BLE协议栈上层的数据结构和组织方式. 属性(Attribute)概念是ATT层的核心,ATT层定义了属性的内容, ...
随机推荐
- AWVS漏洞测试-03节-添加扫描项目
http://localhost:9660 我们要扫描这个页面 点击左上角的New Scan,在Scan Single哪里输入要扫描的网站地址,可以是本地地址 然后选择下一步 Next 这里我们可以配 ...
- 昨日尝试使用百度死链提交,使用lCGI规则提交
本来打算去掉北盟网校的死链,但就算配了规则,提交百度,但是好像还是没有删除到 认真阅读了百度的死链工具 好像需要将死链返回404错误提示 检查北盟的代码,发现北盟做了404从定向 在程序里面404从定 ...
- 深入剖析 redis 主从复制
主从概述 redis 支持 master-slave(主从)模式,redis server 可以设置为另一个 redis server 的主机(从机),从机定期从主机拿数据.特殊的,一个 从机同样可以 ...
- Navi.Soft30.产品.阅读导航
Navi.Soft30.Core类库.开发手册 Navi.Soft30.框架.WinForm开发手册 Navi.Soft30.框架.WebMVC开发手册 Navi.Soft30.框架.Mobile.开 ...
- Web 技术人员需知的 Web 缓存知识(转)
最近的译文距今已有4年之久,原文有一定的更新.今天踩着前辈们的肩膀,再次把这篇文章翻译整理下.一来让自己对web缓存的理解更深刻些,二来让大家注意力稍稍转移下,不要整天HTML5, 面试题啊叨啊叨的~ ...
- 【原】 COCOS2D—LUA 获取剪贴板内容
android下: local luaj = require ("framework.luaj") local ok,ret = luaj.callStaticMethod( ...
- mysql 性能优化 配置优化
http://download.csdn.net/album/detail/1397/2
- 深入理解图优化与g2o:图优化篇
前言 本节我们将深入介绍视觉slam中的主流优化方法——图优化(graph-based optimization).下一节中,介绍一下非常流行的图优化库:g2o. 关于g2o,我13年写过一个文档,然 ...
- toad 常用快捷键与配置
F8 调出以前执行的sql命令 F9 执行全部sql Ctrl+. 补全table_name Ctrl+t 补全table_name,或者显示字段 alt+ 箭头上下 看sql history Ctr ...
- Qt snippet — 打开文件&保存文件
打开文件: void Notepad::on_actionOpen_triggered() { QString fileName = QFileDialog::getOpenFileName(this ...