问题描述
在我的应用程序中,几个模型需要 Password
属性(例如,Registration
和 ChangePassword
模型).Password
属性具有 DataType
和 Required
等属性.因此,为了确保可重用性和一致性,我创建了:
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.
找到 答案来自微软:
产品团队不想实现这个功能,主要是因为两个原因:
The product team does not want to implement this feature, for two main reasons:
- 与 DataAnnotations.Validator 的一致性
- 与 ASP.Net MVC 中的验证行为一致
- 棘手的场景:一个类实现了两个具有相同属性但属性冲突的接口.哪个属性会优先吗?
这篇关于接口成员的属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!