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

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

问题描述

在我的应用程序的几款机型需要密码属性(例如,注册的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屋!

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