Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - Attribute on Interface members does not work

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; }
} 

And

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; }
}

And

public class RegistrationModel : PasswordContainer {
    public override string Password { get; set; }
}

Now it is working. Why it is so?

Why the attributes are working when inherited from class but not working when inherited from interface?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Attributes on interface properties doesn't get inherited to the class, you may make your interface an Abstract Class.

Found an answer from Microsoft:

The product team does not want to implement this feature, for two main reasons:

  • Consistency with DataAnnotations.Validator
  • Consistency with validation behavior in ASP.Net MVC
  • tricky scenario: a class implements two interfaces that have the same property, but with conflicting attributes on them. Which attribute would take precedence?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...