有没有办法从继承的属性中删除属性?
是否可以从继承的属性中删除属性?我认为通过使用 new 关键字我可以这样做......
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 专门用于隐藏继承的成员。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 Employee 类现在有 2 个 FirstName 属性,其中一个仍然是 [Required] ...
直接回答:不,据我所知,您无法删除属性。这将违反替代原则。当 Employee IS-A Person 时,Person.FirstName 的属性适用。
并且:这里的
new
关键字仅用于抑制“X正在隐藏基类成员..”警告。它对代码的语义没有任何影响。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.