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

1 に答える 1

1

正規表現の検証属性を使用するだけの場合は、から継承できます。その方法の例については、https://stackoverflow.com/a/8431253/486434RegularExpressionAttributeを参照してください。

ただし、より複雑なことを行い、値にアクセスする場合は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);
    }
}
于 2012-12-20T12:59:46.397 に答える