是否可以在C#中继承数据注释?

jen*_*ens 5 c# data-annotations

我可以在另一个类中继承"密码"数据注释吗?

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

另一类:

    public class PasswordReset : AccountCredentials
{
    [Required]
    public string resetToken { get; set; }
    **["use the same password annotations here"]**
    public string newPassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

由于API调用,我必须使用不同的模型,但是要避免必须为同一字段维护两个定义.谢谢!

增加:类似的东西

[UseAnnotation[AccountCredentials.password]]
public string newPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)

Eri*_*rer 5

考虑使用组合优于继承并使用Money模式.

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

也许它对我来说已经成为一把金钥匙,但最近我在这方面取得了很大的成功,特别是在创建基类之间做出选择,或者改为采用共享行为并将其封装在对象中时.继承可能会很快失控.