C#屬性(Attribute)用法實例解析

屬性(Attribute)是C#程序設計中很是重要的一個技術,應用範圍普遍,用法靈活多變。本文就以實例形式分析了C#中屬性的應用。具體入戲:javascript

1、運用範圍html

程序集,模塊,類型(類,結構,枚舉,接口,委託),字段,方法(含構造),方法,參數,方法返回值,屬性(property),Attributejava

複製代碼
[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的定義。 this

2、自定義Attributespa

爲了符合「公共語言規範(CLS)」的要求,全部的自定義的Attribute都必須繼承System.Attribute。設計

第一步:自定義一個檢查字符串長度的Attribute3d

複製代碼
[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上,內建一個帶參的構造器,讓外部傳入要求的最大長度。code

第二步:建立一個實體類來運行咱們自定義的屬性orm

複製代碼
public class People
{
  [StringLength(8)]
  public string Name { get; set; }
 
  [StringLength(15)]
  public string Description { get; set; }
}
複製代碼

定義了兩個字符串字段Name和Description, Name要求最大長度爲8個,Description要求最大長度爲15.htm

第三步:建立驗證的類

複製代碼
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#程序設計能有必定的幫助做用。

 

https://www.cnblogs.com/ldyblogs/p/attribute.html

相關文章
相關標籤/搜索