接口成员的属性不起作用

Attribute on Interface members does not work(接口成员的属性不起作用)
本文介绍了接口成员的属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,几个模型需要 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 中的验证行为一致
  • 棘手的场景:一个类实现了两个具有相同属性但属性冲突的接口.哪个属性会优先吗?

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)