关于“新” C#中的关键字 [英] Regarding "new" keyword in C#

查看:92
本文介绍了关于“新” C#中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下,

工作正常而不使用new关键字,那么为什么要引入新关键字!!

I have code below,
its working fine without using "new" keyword, then why new keyword has been introduced!!

namespace Question
{
	public class Program
	{
		public void Display ( )
		{
			Console.WriteLine( "Program" );
		}
	}

	public class ProgramB : Program
	{
		public void Display ( )
		{
			Console.WriteLine( "ProgramB" );
		}

		static void Main ( string[ ] args )
		{
			Program obj = new Program( );
			ProgramB objb = new ProgramB( );

			obj.Display( );
			objb.Display( );

			Console.ReadKey( );
		}
	}
}



OutPut:

计划

ProgramB


OutPut:
Program
ProgramB

推荐答案

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[^]


这篇关于关于“新” C#中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆