c# 抽象类+特性 验证QQ,Mobile,Name的通用写法
1. 调用 bool bResult = ValidateAttributeExtension.Validate<StudentVip>(vip);
[Custom]
public class StudentVip : Student
{
[Custom]
public string Description;
//[Custom]
[QQAttribute(_MinLenth = 5, _MaxLenth = 12)]
public string QQ { [Custom(456, "Ricahrd")][Custom(567, "Ricahrd1")][Custom(789, "Ricahrd2")] get; set; }
[MobileNumAtrribute(11)]
public long MobileNum { get; set; }
}
2.特性的额外方法:验证功能:
public class ValidateAttributeExtension
{
public static bool Validate<T>(T t)
{
Type type = t.GetType();
foreach (PropertyInfo prop in type.GetProperties())
{
///验证手机号长度
//if (prop.IsDefined(typeof(MobileNumAtrribute), true))
//{
// object oValue = prop.GetValue(t);
// MobileNumAtrribute atrribute = prop.GetCustomAttribute<MobileNumAtrribute>(true);
// if (!atrribute.Validate(oValue))
// {
// return false;
// }
//}
/////这就是验证QQ
//if (prop.IsDefined(typeof(QQAttribute), true))
//{
// object oValue = prop.GetValue(t);
// QQAttribute atrribute = prop.GetCustomAttribute<QQAttribute>(true);
// if (!atrribute.Validate(oValue))
// {
// return false;
// }
//}
//如果后续还需要再加一个验证呢?那岂不是 又要修改代码?
//这样做是坑,抽象~~
if (prop.IsDefined(typeof(AbstractValidateAttribute), true))
{
object oValue = prop.GetValue(t);
AbstractValidateAttribute atrribute = prop.GetCustomAttribute<AbstractValidateAttribute>(true);
if (!atrribute.Validate(oValue))
{
return false;
}
}
}
return true;
}
}
3.验证QQ的特性继承抽象类+验证QQ的长度
public class QQAttribute: AbstractValidateAttribute
{
public int _MinLenth;
public int _MaxLenth;
public override bool Validate(object mobileNum)
{
return mobileNum != null && mobileNum.ToString().Length >= _MinLenth && mobileNum.ToString().Length <= _MaxLenth;
//if (mobileNum!=null&& mobileNum.ToString().Length>= _MinLenth && mobileNum.ToString().Length<= _MaxLenth)
//{
// return true;
//}
//return false;
}
}
4.抽象类继承特性
public abstract class AbstractValidateAttribute : Attribute
{
public abstract bool Validate(object value);
}
----------------------------------------------------------- 特性应用 -status 枚举 enum------------------------------------------
0.调用
var normal = UserStuta.Normal;
var frozen = UserStuta.Frozen;
string strnormal = RemarkExtension.GetRemark(normal); //获取枚举描述
string strfrozen = RemarkExtension.GetRemark(frozen);
1.remark 扩展
public static class RemarkExtension
{
public static string GetRemark(this Enum @enum) //扩展方法
{
Type type = @enum.GetType();
FieldInfo? fileInfo = type.GetField(@enum.ToString());
if (fileInfo != null)
{
if (fileInfo.IsDefined(typeof(RemarkAttribute), true))
{
RemarkAttribute remarkAttribute = (RemarkAttribute)fileInfo.GetCustomAttribute(typeof(RemarkAttribute), true);
return remarkAttribute.Remark;
}
}
return @enum.ToString();
}
}
2.remark特性
[AttributeUsage(AttributeTargets.Field)]
public class RemarkAttribute : Attribute
{
public string Remark { get; private set; }
public RemarkAttribute(string remark)
{
this.Remark = remark;
}
}