有没有办法从继承的属性中删除属性? [英] Is there a way to remove attributes from an inherited property?
问题描述
是否可以从继承的属性中删除属性?我认为通过使用 new 关键字,我可以做到这一点...
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; }
}
...但这根本不起作用。这让我感到惊讶,因为特别是 new 用来隐藏继承的成员。
... but this doesnt work at all. This surprises me because the new is specifically there to hide inherited members.
推荐答案
您现在的Employee类有2个FirstName属性,其中一个仍为[必需] ...
Your Employee class now has 2 FirstName properties, one of them is still [Required] ...
直接回答:不,就我所知,您无法删除属性。这将违反替代原则。当雇员为IS-A人员时,将应用Person.FirstName的属性。
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.
并且: new
关键字在这里 only 用来禁止显示 X正在隐藏基类成员..警告。它对代码的语义没有任何影响。
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.
这篇关于有没有办法从继承的属性中删除属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!