简体   繁体   English

派生类的C#验证属性

[英]C# validation attributes for derived class

I have a base class with some properties: 我有一些属性的基类:

public class A
{
   [Display(Name = "Some Property")]
   public virtual int SomeProperty {get;set;}
}

and its derived class: 及其派生类:

public class B:A
{
   [Required]
   public override int SomeProperty {get;set;}
}

But in fact, when I extract metadata for class B to ModelMetadata, IsRequired property is set to false. 但是实际上,当我将类B的元数据提取到ModelMetadata时,IsRequired属性设置为false。 Is there a way to apply Required attribute, so it was reflected in ModelMetadata? 有没有一种方法可以应用Required属性,因此它反映在ModelMetadata中?

Please try the example below: 请尝试以下示例:

public class A
{
    [Display(Name = "Some Property")]
    public virtual int SomeProperty { get; set; }
}
public class B : A
{
    [MyRequired]
    public override int SomeProperty { get; set; }
}

[AttributeUsage(AttributeTargets.Property, Inherited = true)]

public class MyRequiredAttribute : RequiredAttribute
{

}

finally: 最后:

代码测试

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

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