Is it possible to inherit data annotations in C#?

痴心易碎 提交于 2019-12-07 05:26:53

问题


Can I inherit the "password" data annotation in another class?

    public class AccountCredentials : AccountEmail
{
    [Required(ErrorMessage = "xxx.")]
    [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]
    public string password { get; set; }
}

The other class:

    public class PasswordReset : AccountCredentials
{
    [Required]
    public string resetToken { get; set; }
    **["use the same password annotations here"]**
    public string newPassword { get; set; }
}

I have to use different models due to API call's, but like to avoid having to maintain two definitions for the same field. Thanks!

Addition: something like

[UseAnnotation[AccountCredentials.password]]
public string newPassword { get; set; }

回答1:


Consider favoring composition over inheritance and using the Money Pattern.

    public class AccountEmail { }

    public class AccountCredentials : AccountEmail
    {
        public Password Password { get; set; }
    }

    public class PasswordReset : AccountCredentials
    {
        [Required]
        public string ResetToken { get; set; }

        public Password NewPassword { get; set; }
    }

    public class Password
    {
        [Required(ErrorMessage = "xxx.")]
        [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]
        public string Value { get; set; }

        public override string ToString()
        {
            return Value;
        }
    }

Perhaps it has become a golden hammer for me, but recently I have had a lot of success with this, especially when given the choice between creating a base class or instead taking that shared behavior and encapsulating it in an object. Inheritance can get out of control rather quickly.




回答2:


In the base class, you can make it virtual property, and change it override in the derived class. However, it would not inherit attribute, we do a tricky here :

public class AccountCredentials : AccountEmail
{
 [Required(ErrorMessage = "xxx.")]
 [StringLength(30, MinimumLength = 6, ErrorMessage = "xxx")]
 public virtual string password { get; set; }
}

public class PasswordReset : AccountCredentials
{
 [Required]
 public string resetToken { get; set; }
 public override string password { get; set; }
}


来源:https://stackoverflow.com/questions/22767350/is-it-possible-to-inherit-data-annotations-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!