与this question一样,我想使用TypeDescriptor来获取一些属性 - 但与那个问题不同,我想只获取已经添加了自定义属性的属性。
这是一个类属性,所以我想获得具有自定义属性的类中的属性。
到目前为止我有什么
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class AtLeastOneValueRequiredClassAttribute : ValidationAttribute
{
public override bool IsValid(object selection)
{
var att = new Attribute[] { new AtLeastOneValueRequiredAttribute() };
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(selection, att);
foreach (var property in properties)
{
if (property != null)
return true;
}
return false;
}
...始终返回所有属性,而不仅仅是具有我的自定义属性属性的属性(AtLeastOneValueRequiredAttribute)。
以下是我将其应用于此类的课程:
[AtLeastOneValueRequiredClassAttribute(ErrorMessage = "You must enter at least one number")]
public class MemberDetails
{
[AtLeastOneValueRequired]
[Display(Name = "Home Phone Number")]
[RegularExpression("([0-9]+)", ErrorMessage = "Please provide a valid Home Phone number")]
public string HomePhoneNumber { get; set; }
[AtLeastOneValueRequired]
[Display(Name = "Work Phone Number")]
[RegularExpression("([0-9]+)", ErrorMessage = "Please provide a valid Work Phone number")]
public string WorkPhoneNumber { get; set; }
[AtLeastOneValueRequired]
[Display(Name = "Fax Number")]
[RegularExpression("([0-9]+)", ErrorMessage = "Please provide a valid Fax number")]
public string FaxNumber { get; set; }
[AtLeastOneValueRequired]
[Display(Name = "Mobile Number")]
[RegularExpression("([0-9]+)", ErrorMessage = "Please provide a valid Mobile Phone number")]
public string MobileNumber { get; set; }
}