1. 程式人生 > >c#核心基礎 - 淺談 c# 中的特性 Attribute)

c#核心基礎 - 淺談 c# 中的特性 Attribute)

des read pri set cat 允許 開源 custom 體系

特性(Attribute)是用於在運行時傳遞程序中各種元素(比如類、方法、結構、枚舉、組件等)的行為信息的聲明性標簽。可以通過使用特性向程序添加聲明性信息。一個聲明性標簽是通過放置在它所應用的元素前面的方括號[ ]來描述的。

.Net 框架提供了兩種類型的特性:預定義特性和自定義特性。

一、運用範圍

程序集,模塊,類型(類,結構,枚舉,接口,委托),字段,方法(含構造),方法,參數,方法返回值,屬性(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(8)]
  public string Name { get; set; }
 
  [StringLength(15)]
  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#核心基礎 - 淺談 c# 中的特性 Attribute)