2012-12-20 4 views
2

속성 클래스 내부의 속성 값에 액세스하려면 어떻게해야합니까? 정규 표현식에 대해 속성의 값을 확인해야하는 사용자 지정 유효성 검사 특성을 작성하고 있습니다. 인스턴스에 대한 : 당신은 그냥 정규식 유효성 검사 속성을 사용하려면, 다음 RegularExpressionAttribute에서 상속 할 수속성이있는 속성 값에 액세스

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

, 그 작업을 수행하는 방법의 예를 들어 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); 
    } 
} 
관련 문제