【问题标题】:Test for Attributes From Within the Code of Other Attributes测试其他属性代码中的属性
【发布时间】:2012-05-24 10:06:24
【问题描述】:

是否可以在另一个属性的代码中测试一个属性是否存在?

假设你有以下类定义:

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

... MyTestAttribute.IsValid 是否可以确定 Inception.Levels 是否具有RequiredAttribute?

【问题讨论】:

  • 哦哦!好一个!我猜不是,但这只是一个猜测。

标签: c# reflection custom-attributes


【解决方案1】:

ValidationAttribute 的特定情况下,这是可能的,但您必须使用具有上下文参数的另一个 IsValid 重载。上下文可用于获取包含类型,也可用于获取应用属性的属性的名称。

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

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2017-12-16
    • 1970-01-01
    • 2019-06-09
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多