2012-05-16 9 views
6

Czy można przetestować istnienie atrybutu w kodzie innego atrybutu?Test atrybutów z kodu innych atrybutów

Powiedzmy, że masz następującą definicję klasy:

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

... czy to możliwe, aby ustalić, czy MyTestAttribute.IsValid Inception.Levels ma RequiredAttribute?

+0

Ooooh! Dobry! Zgaduję, że nie, ale to tylko domysły. – zmbq

Odpowiedz

3

W konkretnym przypadku ValidationAttribute jest to możliwe, ale należy użyć innego przeciążenia IsValid, które ma parametr kontekstu. Kontekstu można użyć, aby uzyskać typ zawierający, a także uzyskać nazwę właściwości, do której atrybut jest stosowany.

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