接口成员上的属性不起作用 [英] Attribute on Interface members does not work

查看:24
本文介绍了接口成员上的属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,几个模型需要 Password 属性(例如,RegistrationChangePassword 模型).Password 属性具有类似 DataTypeRequired 的属性.因此,为了确保可重用性和一致性,我创建了 :

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 中的验证行为保持一致
  • 棘手的场景:一个类实现了两个具有相同属性但属性相互冲突的接口.哪一个属性优先?

这篇关于接口成员上的属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆