1.特性定义
[AttributeUsage(AttributeTargets.Property)]
public class VerificationAttribute : Attribute
{
public bool IsEmpty => true;
public VerificationAttribute()
{
}
}
2.定义在属性上
/// <summary>
/// 域名
/// </summary>
[Verification]
public string FieldName { get; set; } = "FIELD_NAME";
/// <summary>
/// 值名
/// </summary>
[Verification]
public string FieldValue { get; set; } = "FIELD_VAL";
3.基类实现,通过特性的方式去校验指定数据是否为空,判断list是否为空
protected bool CanSave()
{
Type property = Setting.GetType();
var list = property.GetProperties().ToList();
foreach (var item in list)
{
VerificationAttribute? attribute = (VerificationAttribute?)item.GetCustomAttribute(typeof(VerificationAttribute));
if (attribute != null)
{
var proValue = item.GetValue(Setting);
if (proValue == null)
return false;
else if (item.PropertyType == typeof(string))
{
if (string.IsNullOrEmpty(proValue.ToString()?.Trim()))
return false;
}
else if (item.PropertyType == typeof(bool))
{
if (!(bool)proValue)
return false;
}
else if (typeof(IEnumerable).IsAssignableFrom(item.PropertyType))
{
IEnumerable<object>? enumerable = proValue as IEnumerable<object>;
if (enumerable == null)
return false;
if (!enumerable.Any())
return false;
}
else
return false;
}
}
return true;
}
文章评论