且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

关于“新” C#中的关键字

更新时间:2023-01-13 07:38:53

MSDN 中所述> [ ^ ]新修饰符仅限用于显式隐藏具有相同名称的基本成员,并将其替换为派生成员。除了抑制编译器警告没有其他目的。您的代码将按原样运行,但请检查编译器输出以获取警告。警告是为了让您知道您可能意外隐藏基本成员。使用new你基本上是告诉编译器你知道你在做什么。
As stated in MSDN[^] the new modifier is only used to explicitly hide the base member with the same name and replace it with the derived one. There is no other purpose than suppressing the compiler warning. Your code will work as it is now, check the compiler output for the warning though. The warning is there to let you know that you may accidentally be hiding the base member. Using new you are basically saying to the compiler that you know what you are doing.


你正在使用 new

You are using new:
Program obj = new Program( );
ProgramB objb = new ProgramB( );

如果没有它们,你的程序就无法运行了。



让我们退一步看看 new 确实。

申报变量时:

And without them, your program woudln't work.

Let's just step back a bit and look at what new does.
When you declare a variable:

Program p;

引用分配内存到Program对象:它不会创建Program类的实例。在您通过 new 关键字明确说给我一个程序实例之前,不会创建它:

You allocate memory for a reference to a Program object: that doesn't create an instance of a Program class. That isn't created until you explicitly say "give me a Program instance" via the new keyword:

p = new Program();



它就像一个停车位:它是一个可以包含一个变量的变量汽车,但直到你停在那里它是空的:你不能离开你的房子,开车,开走。 关键字将车停放在停车位,现在您可以开车到商店了!


It's like a car parking space: it's a variable that can contain a car, but until you park there it is empty: you can't leave your house, start the car, and drive away. The new keyword "parks the car in the parking space" and now you can drive to the shops!


您必须了解多态性如何在OOP和C#中 - http://msdn.microsoft.com/en-us/library /ms173152.aspx [ ^ ]

在该树下有一个特定页面可以解决您的问题: http: //msdn.microsoft.com/en-us/library/ms173153.aspx [ ^ ]
You have to learn about how Polymorphism is in OOP and in C# - http://msdn.microsoft.com/en-us/library/ms173152.aspx[^]
Under that tree there is a specific page addressing your question: http://msdn.microsoft.com/en-us/library/ms173153.aspx[^]