1. 主页
  2. 文档
  3. C#进阶
  4. 第四章 特性
  5. 第四节 特性实验三

第四节 特性实验三

创建一个继承自Attribute的特性类AbstractValidateAttribute.cs类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.ValidateExtends
{
    public abstract class AbstractValidateAttribute:Attribute
    {
        public abstract bool Validate(object objValue);
    }
}

创建一特性扩展的类泛型实现扩展方法ValidateExtends.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.ValidateExtends
{
    /// <summary>
    /// 泛型扩展方法实现
    /// </summary>
    public static class AttributeExtend
    {
        public static bool Validate<T>(this T t)
        {
            Type type = t.GetType();
            foreach (var property in type.GetProperties())
            {
                if (property.IsDefined(typeof(AbstractValidateAttribute),true))
                {
                    object objValute = property.GetValue(t);
                    foreach (AbstractValidateAttribute attribute in property.GetCustomAttributes(typeof(AbstractValidateAttribute),true))
                    {
                        if (!attribute.Validate(objValute)) //如果成功就继续验证,否则返回
                        {
                            return false;
                        }
                    }
                }
            }
            return true;
        }
    }
}

创建一个LongAttribute特性扩展类继承AbstractValidateAttribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.ValidateExtends
{
    [AttributeUsage(AttributeTargets.Property)]
    public class LongAtrribute : AbstractValidateAttribute
    {
        private long _Long = 0;
        /// <summary>
        /// 有参构造函数
        /// </summary>
        /// <param name="phoneLength"></param>
        public LongAtrribute(long phoneLength)
        {
            this._Long = phoneLength;
        }
        public override bool Validate(object objValue)
        {
           return objValue != null && objValue.ToString().Length == 11;
        }
    }
}

创建一个RequiredAttribute特性扩展类继承AbstractValidateAttribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.ValidateExtends
{
    [AttributeUsage(AttributeTargets.Property)]
    public class RequiredAttribute : AbstractValidateAttribute
    {
        public override bool Validate(object objValue)
        {
            return objValue != null && !string.IsNullOrWhiteSpace(objValue.ToString());
        }
    }
}

创建一个StringLengthAttribute特性扩展类继承AbstractValidateAttribute

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.ValidateExtends
{
    [AttributeUsage(AttributeTargets.Property)]
    public class StringLengthAttribute : AbstractValidateAttribute
    {
        private int _Mini = 0;
        private int _Max = 0;
        public StringLengthAttribute(int min,int max)
        {
            this._Max = max;
            this._Mini = min;
        }
        public override bool Validate(object objValue)
        {
           return objValue != null
                && objValue.ToString().Length >= this._Mini
                && objValue.ToString().Length <= this._Max;
        }
    }
}

创建一个使用类来实例化特性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyAttribute.ValidateExtends
{
    public class Study
    {
        public int Id { get; set; }
        [Required]
        [StringLength(5,10)]    //名称的字符长度是5~10
        public string StudyName { get; set; }
        [Required]
        [LongAtrribute(11)]    //电话的长度11位
        public long PhoneNum { get; set; }

    }
}

在Main函数中的调用

static void Main(string[] args)
{
      Study study = new Study()
      {
           Id = 1,
           PhoneNum=12345678900,
           StudyName= "开发者开发者"   
       };
       if (study.Validate())
       {
            Console.WriteLine("验证成功");
       }
       else
       {
             Console.WriteLine("验证失败");
        }
       Console.ReadKey(); 
}
这篇文章对您有用吗?

我们要如何帮助您?