是否可以在C#中继承数据注释? [英] Is it possible to inherit data annotations in C#?
本文介绍了是否可以在C#中继承数据注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以在另一个类中继承密码数据注释吗?
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; }
}
另一类:
public class PasswordReset : AccountCredentials
{
[Required]
public string resetToken { get; set; }
**["use the same password annotations here"]**
public string newPassword { get; set; }
}
由于API调用的原因,我不得不使用不同的模型,但要避免必须为同一字段维护两个定义。
谢谢!
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!
添加:类似
[UseAnnotation[AccountCredentials.password]]
public string newPassword { get; set; }
推荐答案
考虑在继承中优先考虑组成,并使用货币模式。
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.
这篇关于是否可以在C#中继承数据注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文