1. 程式人生 > 資訊 >北京地鐵 318 座車站實現 AED(自動體外除顫器)裝置全覆蓋

北京地鐵 318 座車站實現 AED(自動體外除顫器)裝置全覆蓋

Attribute的作用是為元資料新增內容,即可用來標註一段程式,可以是類,屬性,方法等。可利用反射機制獲取標註或者獲取標註的屬性,類或者方法等,用來執行不同的操作,例如資料的校驗等。

自定義特性

類名必須以Attribute結尾,需要繼承.NET提供的Attribute抽象類。

C#中的 欄位(Field)與屬性(Property)

  • 欄位是值私有屬性。

  • 屬性是指訪問器,含get{}或set{}的程式碼塊的特殊“方法”。

 // 定義特性可以使用的目標
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,AllowMultiple = true)]
class LengthAttribute : Attribute
{
    public int MinimumLength { get; set; }
    public int Maximum { get; set; }

    public LengthAttribute(int minimumLength, int maximum)
    {
        MinimumLength = minimumLength;
        Maximum = maximum;
    }

    // 驗證特性
    public bool Validate(object value)
    {
        if (!string.IsNullOrWhiteSpace((string)value))
        {
            if(value.ToString().Length>= MinimumLength && value.ToString().Length <= Maximum)
            {
                return true;
            }
        }
        return false; 
    }
}

驗證特性

public class Validatettribute
{
    public static bool Validate<T>(T t)
    {
        // 獲取所有屬性
        var propertyInfos = typeof(T).GetProperties();
        // 遍歷所有屬性
        foreach(var property in propertyInfos)
        {
            // 判斷特性是否定義(注:多個特性可以繼承自一個抽象類,直接判斷抽象類是否定義)
            if (property.IsDefined(typeof(LengthAttribute), true))
            {
                // 獲取屬性上的所有特性
                var attributes = property.GetCustomAttributes();
                // 遍歷所有特性
                foreach(var attribute in attributes)
                {
                    LengthAttribute lengthAttribute = (LengthAttribute)attribute;
                    // 呼叫特性的驗證方法 傳入屬性的值
                    return lengthAttribute.Validate(property.GetValue(t));
                }
            }
        }
        return false;
    }
}

使用特性

public class Student
 {
     public int Id { get; set; }
     [Length(1,50)]// 字串長度校驗
     public string Name { get; set; }
 }
class Program
{
    static void Main(string[] args)
    {
        Student stu = new Student { Name = "" };
        Console.WriteLine(Validatettribute.Validate<Student>(stu));// False
        Student stu1 = new Student { Name = "zhang" };
        Console.WriteLine(Validatettribute.Validate<Student>(stu1));// True
    }
}