属性上的接口成员不起作用 [英] Attribute on Interface members does not work
问题描述
在我的应用程序的几款机型需要密码
属性(例如,注册
和的ChangePassword
型号)。在密码
属性有属性,比如数据类型
和要求
。因此,要确保重用性的一致性,我创建了:
In my application several models need Password
properties (eg, Registration
and ChangePassword
models). The Password
property has attribute like DataType
and Required
. Therefore to ensure of re-usability an consistency, I created :
interface IPasswordContainer{
[Required(ErrorMessage = "Please specify your password")]
[DataType(DataType.Password)]
string Password { get; set; }
}
和
class RegistrationModel : IPasswordContainer {
public string Password { get; set; }
}
不幸的是,该属性不工作
Unfortunately, the attributes does not work.
然后我试图接口更改为一个类:
Then I tried changing the interface to a class:
public class PasswordContainer {
[Required(ErrorMessage = "Please specify your password")]
[DataType(DataType.Password)]
public virtual string Password { get; set; }
}
和
public class RegistrationModel : PasswordContainer {
public override string Password { get; set; }
}
现在它正在工作。为什么会这样?
Now it is working. Why it is so?
为什么属性正在从类继承,但是当从接口?继承不工作时
推荐答案
在接口属性属性不会被继承的类,你可以让你的界面的抽象类。
Attributes on interface properties doesn't get inherited to the class, you may make your interface an Abstract Class.
发现的<一个href=\"http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/1748587a-f13c-4dd7-9fec-c8d57014632c/\">answer从微软:
该产品团队不希望实现此功能,主要有两个
原因:
The product team does not want to implement this feature, for two main reasons:
- 一致性与DataAnnotations.Validator
- 一致性与ASP.Net MVC的验证行为
- 棘手的情景:一个类实现具有相同属性的两个接口,但对他们的冲突的属性。哪一个
属性会采取precedence?
这篇关于属性上的接口成员不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!