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

时间:2023-02-26 19:37:08

属性(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#属性(Attribute)用法实例解析的更多相关文章

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

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

  2. mysql中limit的用法实例解析

    mysql中limit的用法解析. 在mysql中,select * from table limit m,n.其中m是指记录开始的index,从0开始,n是指从第m条开始,取n条. 例如: mysq ...

  3. python的模块future用法实例解析

    计算机的知识太多了,很多东西就是一个使用过程中详细积累的过程.最近遇到了一个很久关于future的问题,踩了坑,这里就做个笔记,免得后续再犯类似错误.   future的作用:把下一个新版本的特性导入 ...

  4. python中super的用法实例解析

    概念 super作为python的内建函数.主要作用如下: 允许我们避免使用基类 跟随多重继承来使用 实例 在单个继承的场景下,一般使用super来调用基类来实现: 下面是一个例子: class Ma ...

  5. python命令行参数解析OptionParser类用法实例

    python命令行参数解析OptionParser类用法实例 本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考. 具体代码如下:     from opt ...

  6. sql server 计算属性,计算字段的用法与解析

    SQL学习之计算字段的用法与解析   一.计算字段 1.存储在数据库表中的数据一般不是应用程序所需要的格式.大多数情况下,数据表中的数据都需要进行二次处理.下面举几个例子. (1).我们需要一个字段同 ...

  7. jQuery中attr()方法用法实例

    本文实例讲述了jQuery中attr()方法用法.分享给大家供大家参考.具体分析如下: 此方法设置或返回匹配元素的属性值. attr()方法根据参数的不同,功能也不同. 语法结构一: 获取第一个匹配元 ...

  8. pyquery 的用法 --爬虫解析库

    如果你对Web有所涉及,如果你比较喜欢用CSS选择器,如果你对jQuery有所了解,那么这里有一个更适合你的解析库--pyquery. 接下来,我们就来感受一下pyquery的强大之处. 1. 准备工 ...

  9. python中argparse模块用法实例详解

    python中argparse模块用法实例详解 这篇文章主要介绍了python中argparse模块用法,以实例形式较为详细的分析了argparse模块解析命令行参数的使用技巧,需要的朋友可以参考下 ...

随机推荐

  1. Xcode常用代码块

    Xcode的代码片段(Code Snippets)创建自定义的代码片段,当你重用这些代码片段时,会给你带来很大的方便. 常用的: 1.strong:@property (nonatomic,stron ...

  2. java.outOfMemory

    http://www.kdgregory.com/index.php?page=java.outOfMemory Java Platform, Standard Edition HotSpot Vir ...

  3. 10 Useful du (Disk Usage) Commands to Find Disk Usage of Files and Directories

    The Linux “du” (Disk Usage) is a standard Unix/Linux command, used to check the information of disk ...

  4. supermap开发webgis的经验

    SuperMap 开发WebGIS的经验总结 - 综合课件 - 道客巴巴 http://www.doc88.com/p-743552004620.html

  5. Python绘制3d螺旋曲线图实例代码

    Axes3D.plot(xs, ys, *args, **kwargs) 绘制2D或3D数据 参数 描述 xs, ys X轴,Y轴坐标定点 zs Z值,每一个点的值都是1 zdir 绘制2D集合时使用 ...

  6. 企业安全建设之搭建开源SIEM平台

    https://www.freebuf.com/special/127172.html https://www.freebuf.com/special/127264.html https://www. ...

  7. 对话框 AlterDialog

    AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("尊敬的用户"); bu ...

  8. Codeforces Round #485 Div. 1 vp记

    A:对每种商品多源bfs一下每个点到该商品的最近距离,对每个点sort一下取前s个即可. #include<iostream> #include<cstdio> #includ ...

  9. destoon源码解读

    一.module module值:表示模块的id ID1.核心: ID2.会员: ID3.扩展: 当ID>3时,为购买.公司等模块. dt:为各种变量,相当于整站的配置,如:关键词.描述.积分等 ...

  10. C&num;代码分析(第三周)

    阅读下面程序,请回答如下问题: 问题1:这个程序要找的是符合什么条件的数? 问题2:这样的数存在么?符合这一条件的最小的数是什么? 问题3:在电脑上运行这一程序,你估计多长时间才能输出第一个结果?时间 ...