从其他属性的代码中测试属性

Pat*_*ell 6 c# reflection custom-attributes

是否可以测试另一个属性的代码中是否存在属性?

假设您有以下类定义:

public class Inception {
    [Required]
    [MyTest]
    public int Levels { get; set; }
}
public class MyTestAttribute : ValidationAttribute {
    public override bool IsValid(object o){
        // return whether the property on which this attribute
        // is applied also has the RequiredAttribute
    }
}
Run Code Online (Sandbox Code Playgroud)

... MyTestAttribute.IsValid是否可以确定Inception.Levels是否具有RequiredAttribute?

And*_*bel 3

在 a 的特定情况下ValidationAttribute,这是可能的,但您必须使用IsValid具有上下文参数的其他重载。上下文可用于获取包含类型,还可以获取应用该特性的属性的名称。

protected override ValidationResult IsValid(object value, 
  ValidationContext validationContext)
{
  var requiredAttribute = validationContext.ObjectType
    .GetPropery(validationContext.MemberName)
    .GetCustomAttributes(true).OfType<RequiredAttribute>().SingleOrDefault();
}
Run Code Online (Sandbox Code Playgroud)