简体   繁体   English

将属性添加到覆盖的属性

[英]Add attributes to overridden property

When a base class has a property decorated with validation attributes, is it possible to add more validation attributes within a derived class?当基础 class 具有装饰有验证属性的属性时,是否可以在派生的 class 中添加更多验证属性?

In the following example, Property has both attributes, but validation using the attribute on the base class doesnt seem to work.在以下示例中, Property具有这两个属性,但使用基础 class 上的属性进行验证似乎不起作用。

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

Turns out it's as simple as adding an extra parameter to the Validator.TryValidateObject call:原来它就像在Validator.TryValidateObject调用中添加一个额外的参数一样简单:

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

Doing this now includes the attribute validation on the properties from the base class.现在执行此操作包括对基础 class 的属性进行属性验证。

Credit to this answer .归功于这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM