可重用性的自定义数据注释继承

时间:2017-06-22 13:27:03

标签: c# asp.net .net asp.net-mvc data-annotations

假设您有一个包含电子邮件属性的类,其中包含一些数据注释

public class Person
{
    [Display(Name = "Email address")]
    [Required(ErrorMessage = "The email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [CustomDataAnnotation()]
    public string Email { get; set; }
}

现在您需要另一个具有相同数据注释的电子邮件属性的类

public class Invoice
    {
        [Display(Name = "Email address")]
        [Required(ErrorMessage = "The email address is required")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        [CustomDataAnnotation()]
        public string Email { get; set; }
    }

有没有办法创建一个继承所有其他数据注释的新数据注释[MyEmail]?像这样的东西

    [Display(Name = "Email address")]
    [Required(ErrorMessage = "The email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [CustomDataAnnotation()]
    public DataAnnoation MyEmail {get;set;}

然后能够像这样重用它。

public class Person
    {
        [MyEmail]
        public string Email { get; set; }
    }

public class Invoice
    {
        [MyEmail]
        public string Email { get; set; }
    }

我知道可以使用抽象类,但我不喜欢在另一个类中隐藏Email属性,这使得它更难阅读。

public abstract class MyEmail
{
    [Display(Name = "Email address")]
    [Required(ErrorMessage = "The email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [CustomDataAnnotation()]
    public string Email { get; set; }
}

public class Person : MyEmail {}
public class Invoice : MyEmail { }

任何有关使数据注释更具可重用性的建议表示赞赏。

1 个答案:

答案 0 :(得分:2)

您可以在Person和Invoice类的顶部使用[MetadataType]属性来使用MyEmail类data.annatotaions属性。你可以实现如下。

[MetadataType(typeof(MyEmail))]
public class Person
{
    public string Email { get; set; }
}

[MetadataType(typeof(MyEmail))]
public class Invoice
{
    public string Email { get; set; }
}

public abstract class MyEmail
{
    [Display(Name = "Email address")]
    [Required(ErrorMessage = "The email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    [CustomDataAnnotation()]
    public string Email { get; set; }
}