[英]I can hide an inherited member without the new operator so when why utilize it to do so?
From what I have tested in code it seems like there is no point in using the new
operator to hide an inherited member.从我在代码中测试的内容来看,似乎没有必要使用new
运算符来隐藏继承的成员。 So why even utilize the new
operator to do so?那么为什么还要使用new
运算符来这样做呢?
public class Test
{
public static void Main(string[] args)
{
Bar temp = new Bar();
temp.GetMessage();
}
}
public class Foo
{
public void GetMessage()
{
Console.WriteLine("Message Foo");
}
}
public class Bar : Foo
{
public void GetMessage()
{
Console.WriteLine("Message Bar");
}
}
//output: Message Bar
Lets visit the documentation让我们访问文档
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class.当用作声明修饰符时,new 关键字显式隐藏从基类继承的成员。 When you hide an inherited member, the derived version of the member replaces the base class version.当您隐藏继承的成员时,该成员的派生版本将替换基类版本。 This assumes that the base class version of the member is visible, as it would already be hidden if it were marked as private or, in some cases, internal.这假设成员的基类版本是可见的,因为如果它被标记为私有或在某些情况下是内部的,它就已经被隐藏了。 Although you can hide public or protected members without using the new modifier, you get a compiler warning .尽管您可以在不使用 new 修饰符的情况下隐藏 public 或 protected 成员,但您会收到编译器警告。 If you use new to explicitly hide a member, it suppresses this warning.如果您使用 new 显式隐藏成员,则会取消此警告。
The warning is to primarily warn you what you are about to do, and the new modifier is to explicitly show you (and your team mates, and the poor coders who come after you) what you have reasoned about and considered.警告主要是警告你你将要做什么,而新的修饰符是明确地向你(和你的队友,以及跟随你的可怜的编码人员)展示你的推理和考虑。 Ignore it at your own peril and the ire of anyone who maintains your code忽略它,后果自负,并且会激怒维护您代码的任何人
Its worth noting, using the new modifier like this is generally fairly suspect, and could point to a design problem.值得注意的是,像这样使用new 修饰符通常是相当可疑的,并且可能指向设计问题。 It is a lot more common to override the member instead of replacing it, and much less likely to cause hard to debug runtime errors in production.覆盖成员而不是替换成员更为常见,并且不太可能在生产中导致难以调试的运行时错误。
Extending your example slightly;稍微扩展您的示例;
Bar temp = new Bar();
temp.GetMessage();
Foo temp2 = temp;
temp2.GetMessage();
What output do you expect?你期望什么输出?
Most developers would want Bar.GetMessage()
to be called in both cases.大多数开发人员都希望在这两种情况下都调用Bar.GetMessage()
。 In which case what you actually want is;在这种情况下,您真正想要的是;
public class Foo {
public virtual void GetMessage() { ... }
}
public class Bar : Foo {
public override void GetMessage() { ... }
}
But if you absolutely must have temp.GetMessage()
and ((Foo)temp).GetMessage()
execute different functions.但是,如果您绝对必须让temp.GetMessage()
和((Foo)temp).GetMessage()
执行不同的功能。 Then you need to use the new
modifier to tell the compiler that you know what you are doing, and don't need to see a warning.然后你需要使用new
修饰符告诉编译器你知道你在做什么,不需要看到警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.