Is there a way to remove attributes from an inherited property?

巧了我就是萌 提交于 2019-12-08 15:51:53

问题


Is it possible to remove attributes from inherited properties? I thought that by using the new keyword I could do so...

 public class Person
 {
     [Required]
     public string FirstName { get; set; }

     [Required]
     public string LastName { get; set; }
 }

 public class Employee : Person
 {
     [Required]
     public string JobTitle { get; set; }

     public new string FirstName { get; set; }
 }

... but this doesnt work at all. This surprises me because the new is specifically there to hide inherited members.


回答1:


Your Employee class now has 2 FirstName properties, one of them is still [Required] ...

Direct answer: No, you cannot remove attributes for as far as I know. That would violate the substitution principle. When an Employee IS-A Person then the properties of Person.FirstName apply.

And: the new keyword here only serves to suppress the 'X is hiding base class member..' warning. It has no effect whatsoever on the semantics of your code.



来源:https://stackoverflow.com/questions/3367104/is-there-a-way-to-remove-attributes-from-an-inherited-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!