【发布时间】: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