【问题标题】:Add attributes to overridden property将属性添加到覆盖的属性
【发布时间】:2021-02-01 20:46:14
【问题描述】:

当基类有一个用验证属性修饰的属性时,是否可以在派生类中添加更多验证属性?

在以下示例中,Property 具有两个属性,但使用基类上的属性进行验证似乎不起作用。

public abstract class BaseClass
{
    [StringLength(2, MinimumLength = 1)]
    public virtual string Property { get; set; }
}

public class DerivedClass : BaseClass
{
    [Required]
    public override string Property { get; set; }
}

var obj = new DerivedClass
{
    Property = "123" // Length is greater than max length of 2
};

var requiredAttr = obj.GetType()
    .GetProperty(nameof(obj.Property))
    .GetCustomAttribute<RequiredAttribute>(); // Attribute retrieved - it exists

var stringLengthAttr = obj.GetType()
    .GetProperty(nameof(obj.Property))
    .GetCustomAttribute<StringLengthAttribute>(); // // Attribute retrieved - it exists

var results = new List<ValidationResult>();
Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), results); 
// No validation errors

【问题讨论】:

    标签: c# validation inheritance


    【解决方案1】:

    原来它就像在Validator.TryValidateObject 调用中添加一个额外的参数一样简单:

    var context = new ValidationContext(obj, null, null);
    Validator.TryValidateObject(obj, context, results, validateAllProperties: true); // No validation errors
    

    现在执行此操作包括对基类的属性进行属性验证。

    归功于this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-28
      • 2021-11-06
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      相关资源
      最近更新 更多