2012-05-16 43 views
6

是否有可能测试另一个属性的代码中是否存在属性?从其他属性的代码中测试属性

假设你有下面的类定义:

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 
    } 
} 

...有可能是MyTestAttribute.IsValid以确定是否Inception.Levels有RequiredAttribute标签?

+0

Ooooh!好的!我猜不是,但这只是一个猜测。 – zmbq

回答

3

ValidationAttribute的特定情况下,您可能需要使用具有上下文参数的其他IsValid重载。该上下文可用于获取包含类型,并获取该属性应用于的属性的名称。

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