见下文,我创建了一个Model
继承自另一个的类BaseModel
,使用 new 关键字然后验证每个实例中的一个。据我所知,它们都使用基本属性。
为了清楚地说明验证例程,我添加了一个控件类ControlModel
。
class Program
{
static void Main(string[] args)
{
ValidationTest<Model>();
ValidationTest<BaseModel>();
ValidationTest<ControlModel>();
Console.Read();
}
private static void WriteAttributeInfo<T>()
{
Console.WriteLine(string.Concat(typeof(T), " attributes:"));
typeof(T).GetProperties().SelectMany(m => m.GetCustomAttributes(true)).Select(a => { Console.WriteLine(a); return a; }).ToList();
}
private static void ValidationTest<T>()
{
object obj = Activator.CreateInstance<T>();
Console.WriteLine(string.Concat(typeof(T), " test: isValid = ", Validator.TryValidateObject(obj, new ValidationContext(obj, serviceProvider: null, items: null), new List<ValidationResult>())));
}
}
class ControlModel
{
public string FirstName { get; set; }
public string Email { get; set; }
}
class BaseModel
{
[RequiredAttribute]
public virtual string FirstName { get; set; }
[RequiredAttribute]
public virtual string Email { get; set; }
}
class Model : BaseModel
{
public new string FirstName { get; set; }
public new string Email { get; set; }
}
ConsoleApplication1.Model 测试:isValid = False
ConsoleApplication1.BaseModel 测试:isValid = False
ConsoleApplication1.ControlModel 测试:isValid = True
在此示例中,您似乎无法覆盖/隐藏/忽略继承的必需验证(尚未尝试其他)属性。