程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 特性驗證實體

特性驗證實體

編輯:C#入門知識

using System;
using System.Reflection;

namespace ValidateAgeAttr
{
    class ValidateAgeAttribute : Attribute
    {
        public ValidateAgeAttribute()
        {

        }

        public ValidateAgeAttribute(int maxAge, string validateResult)
        {
            MaxAge = maxAge;
            ValidateResult = validateResult;
        }

        /// <summary>
        /// 允許的最大年齡
        /// </summary>
        public int MaxAge { get; set; }
        /// <summary>
        /// 驗證結果
        /// </summary>
        public string ValidateResult { get; set; }

        public void Validate(int age)
        {
            if (age > MaxAge)
            {
                ValidateResult = string.Format("無法通過驗證:age({0})>MaxAge({1})", age, MaxAge);
            }
            else if (age <= MaxAge)
            {
                ValidateResult = string.Format("驗證通過:age({0})<=MaxAge({1})", age, MaxAge);
            }

        }
    }
    class Person
    {
        public string Name { get; set; }
        //[ValidateAge(MaxAge = 40)]
        [ValidateAge(50, "")]
        public int Age { get; set; }
    }
    class Program
    {
        static void Main()
        {
            var person = new Person { Name = "TT", Age = 20 };
            Type type = person.GetType();
            PropertyInfo propertyInfo = type.GetProperty("Age");
            var validateAgeAttribute = (ValidateAgeAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ValidateAgeAttribute));
            Console.WriteLine("允許的最大年齡:" + validateAgeAttribute.MaxAge);
            validateAgeAttribute.Validate(person.Age);
            Console.WriteLine(validateAgeAttribute.ValidateResult);
            Console.ReadKey();
        }
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved