2012-12-20 158 views
2

如何訪問屬性類內的屬性值。我在寫一個自定義驗證屬性,需要根據正則表達式檢查屬性的值。該 比如:使用屬性訪問屬性值

public class MyAttribute 
{ 
public MyAttribute(){} 

//now this is where i want to use the value of the property using the attribute. The attribute can be use in different classed 
public string DoSomething() 
{ 
//do something with the property value 
} 
} 

Public class MyClass 
{ 
[MyAttribute] 
public string Name {get; set;} 
} 

回答

1

如果你只是想使用正則表達式驗證屬性,那麼你可以從RegularExpressionAttribute繼承,見https://stackoverflow.com/a/8431253/486434對於如何做到這一點的例子。

但是,如果您想要執行更復雜的操作並訪問該值,您可以繼承ValidationAttribute並覆蓋2個虛擬方法IsValid。例如:

public class MyAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     // Do your own custom validation logic here 
     return base.IsValid(value); 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     return base.IsValid(value, validationContext); 
    } 
}