簡體   English   中英

派生類的C#驗證屬性

[英]C# validation attributes for derived class

我有一些屬性的基類:

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

及其派生類:

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

但是實際上,當我將類B的元數據提取到ModelMetadata時,IsRequired屬性設置為false。 有沒有一種方法可以應用Required屬性,因此它反映在ModelMetadata中?

請嘗試以下示例:

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
{

}

最后:

代碼測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM