C# 屬性值的特性驗證樣例

 public abstract class AbstractAttribute : Attribute {
        public AbstractAttribute()
        {

        }
        public abstract bool Validate(object Value);
    }
    public class DataLengthAtribute : AbstractAttribute
    {
        private int _min = 0;
        private int _max = 30;
        public DataLengthAtribute(int min,int max)
        {
            _min = min;
            _max = max;
        }
        public override bool Validate(object Value) {
            if (Value==null||string.IsNullOrEmpty( Value.ToString()))
            {
                return false;
            }
            else
            {
                return Value.ToString().Length >= _min && Value.ToString().Length <= _max;
            }
        }
    public static class ExtendValidate {
        public static bool Validate(object o) {
            Type type = o.GetType();
            foreach (var item in type.GetProperties())
            {
                if (item.IsDefined(typeof(AbstractAttribute),true))
                {
                    AbstractAttribute attribute = (AbstractAttribute)item.GetCustomAttribute(typeof(AbstractAttribute),true);
                    if (!attribute.Validate(item.GetValue(o)))
                    {
                        return false;
                    }  
                }
            }
            return true;
        }
    }

 

 

調用樣例

   public class model {
        [DataLengthAtribute(6,70)]
        public string kk { set; get; }
    }

    model m = new model();
            m.kk = "1235647";
            if (ExtendValidate.Validate(m))
            {
                Console.WriteLine("驗證通過");
            }
            else
            {
                Console.WriteLine("驗證失敗");
            }

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章