Is it possible to inherit data annotations in C#?

十年热恋 提交于 2019-12-05 10:20:59

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.

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