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

问题描述 投票:4回答:2

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

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

另一类:

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

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

增加:类似的东西

[UseAnnotation[AccountCredentials.password]]
public string newPassword { get; set; }
c# data-annotations
2个回答
5
投票

考虑favoring composition over inheritance并使用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;
        }
    }

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


1
投票

在基类中,您可以将其设为virtual属性,并在派生类中更改它override。但是,它不会继承属性,我们在这里做了一件棘手的事情:

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.