【问题标题】:Access property values with an attribute使用属性访问属性值
【发布时间】:2012-12-07 17:52:08
【问题描述】:

如何访问属性类中的属性值。我正在编写一个自定义验证属性,该属性需要根据正则表达式检查属性的值。这 例如:

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

【问题讨论】:

    标签: asp.net-mvc-3 c#-4.0 custom-attributes


    【解决方案1】:

    如果您只想使用正则表达式验证属性,则可以从RegularExpressionAttribute 继承,有关如何执行此操作的示例,请参阅https://stackoverflow.com/a/8431253/486434

    但是,如果您想做一些更复杂的事情并访问您可以从ValidationAttribute 继承的值并覆盖两个虚拟方法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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 2014-09-07
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多