C#屬性(Attribute)用法實(shí)例解析
屬性(Attribute)是C#程序設(shè)計(jì)中非常重要的一個(gè)技術(shù),應(yīng)用范圍廣泛,用法靈活多變。本文就以實(shí)例形式分析了C#中屬性的應(yīng)用。具體入戲:
一、運(yùn)用范圍
程序集,模塊,類型(類,結(jié)構(gòu),枚舉,接口,委托),字段,方法(含構(gòu)造),方法,參數(shù),方法返回值,屬性(property),Attribute
[AttributeUsage(AttributeTargets.All)]
public class TestAttribute : Attribute
{
}
[TestAttribute]//結(jié)構(gòu)
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)//參數(shù)上
{
throw new NotImplementedException();
}
}
這里我們給出了除了程序集和模塊以外的常用的Atrribute的定義。
二、自定義Attribute
為了符合“公共語言規(guī)范(CLS)”的要求,所有的自定義的Attribute都必須繼承System.Attribute。
第一步:自定義一個(gè)檢查字符串長度的Attribute
[AttributeUsage(AttributeTargets.Property)]
public class StringLengthAttribute : Attribute
{
private int _maximumLength;
public StringLengthAttribute(int maximumLength)
{
_maximumLength = maximumLength;
}
public int MaximumLength
{
get { return _maximumLength; }
}
}
AttributeUsage這個(gè)系統(tǒng)提供的一個(gè)Attribute,作用來限定自定義的Attribute作用域,這里我們只允許這個(gè)Attribute運(yùn)用在Property上,內(nèi)建一個(gè)帶參的構(gòu)造器,讓外部傳入要求的最大長度。
第二步:創(chuàng)建一個(gè)實(shí)體類來運(yùn)行我們自定義的屬性
public class People
{
[StringLength(8)]
public string Name { get; set; }
[StringLength(15)]
public string Description { get; set; }
}
定義了兩個(gè)字符串字段Name和Description, Name要求最大長度為8個(gè),Description要求最大長度為15.
第三步:創(chuàng)建驗(yàn)證的類
public class ValidationModel
{
public void Validate(object obj)
{
var t = obj.GetType();
//由于我們只在Property設(shè)置了Attibute,所以先獲取Property
var properties = t.GetProperties();
foreach (var property in properties)
{
//這里只做一個(gè)stringlength的驗(yàn)證,這里如果要做很多驗(yàn)證,需要好好設(shè)計(jì)一下,千萬不要用if elseif去鏈接
//會(huì)非常難于維護(hù),類似這樣的開源項(xiàng)目很多,有興趣可以去看源碼。
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");//這里可以自定義,也可以用具體系統(tǒng)異常類
if (propertyValue.Length > maxinumLength)
throw new Exception(string.Format("屬性{0}的值{1}的長度超過了{(lán)2}", property.Name, propertyValue, maxinumLength));
}
}
}
}
這里用到了反射,因?yàn)锳ttribute一般都會(huì)和反射一起使用,這里驗(yàn)證了字符串長度是否超過所要求的,如果超過了則會(huì)拋出異常
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();
}
希望本文所述實(shí)例對(duì)大家的C#程序設(shè)計(jì)能有一定的幫助作用。
相關(guān)文章
C#實(shí)現(xiàn)塊狀鏈表的項(xiàng)目實(shí)踐
這篇文章主要介紹了C#實(shí)現(xiàn)塊狀鏈表的項(xiàng)目實(shí)踐,通過定義塊和鏈表類,利用塊內(nèi)元素引用實(shí)現(xiàn)塊與塊之間的鏈接關(guān)系,從而實(shí)現(xiàn)對(duì)塊狀鏈表的遍歷、插入和刪除等操作,感興趣的可以了解一下2023-11-11
C#簡(jiǎn)單多線程同步和優(yōu)先權(quán)用法實(shí)例
這篇文章主要介紹了C#簡(jiǎn)單多線程同步和優(yōu)先權(quán)用法實(shí)例,對(duì)于C#線程的阻塞、同步、異步、互斥等概念做了較為深入的分析與實(shí)例講解,需要的朋友可以參考下2014-09-09
C#中List轉(zhuǎn)IList的實(shí)現(xiàn)
本文主要介紹了C#中List轉(zhuǎn)IList的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

