1、首先新建一个抽象类,规范所有的自定义属性
public abstract class CustormAttribute:Attribute
{
public abstract bool Validate(object value);
}
2、新建一个类继承上边的抽象类,实现抽象类的方法
public class RequireAttribute : CustormAttribute
{
public override bool Validate(object value)
{
return value != null
&& !string.IsNullOrWhiteSpace(value.ToString());
}
}
3、给object 写一个扩展方法
public static bool Validate<T>(this T t)
{
Type type = t.GetType();
foreach (var prop in type.GetProperties())
{
if (prop.IsDefined(typeof(CustormAttribute), true))
{
object oValue = prop.GetValue(t);
foreach (CustormAttribute attribute in prop.GetCustomAttributes(typeof(CustormAttribute), true))
{
if (!attribute.Validate(oValue))
return false;
}
}
}
return true;
}
4、新建一个实体类,并在字段上添加 自定义特性
public class Student
{
public int age { get; set; }
[Require]
public string name { get; set; }
}
5、测试
Student st = new Student();
st.Validate();