在方法签名的新关键字 [英] new keyword in method signature

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

问题描述

在执行一个重构,我结束了创建如下例所示的方法。数据类型已改变为简单起见

While performing a refactoring, I ended up creating a method like the example below. The datatype has been changed for simplicity's sake.

我previous过这样的赋值语句:

I previous had an assignment statement like this:

MyObject myVar = new MyObject();

这是偶然的重构,以这样的:

It was refactored to this by accident:

private static new MyObject CreateSomething()
{
  return new MyObject{"Something New"};
}

这是我的一个剪切/粘贴错误的结果,但在关键字私有静态新是有效的,并编译。

This was a result of a cut/paste error on my part, but the new keyword in private static new is valid and compiles.

:什么是关键字的方法签名意味着什么?我认为这件事情中介绍C#3.0?

Question: What does the new keyword signify in a method signature? I assume it's something introduced in C# 3.0?

这是如何从覆盖不同

推荐答案

从MSDN新的关键字参考:

New keyword reference from MSDN:

MSDN参考

下面是我从微软的MVP网,取得了良好的感觉找到了一个例子:
<一href=\"http://social.msdn.microsoft.com/forums/en-US/Vsex$p$pssvcs/thread/65e02299-300f-4b74-8f0a-679f490605f5\">Link到原始

Here is an example I found on the net from a Microsoft MVP that made good sense: Link to Original

public class A
{
   public virtual void One();
   public void Two();
}

public class B : A
{
   public override void One();
   public new void Two();
}

B b = new B();
A a = b as A;

a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B

覆盖只能在非常特殊的情况下使用。从MSDN:

Override can only be used in very specific cases. From MSDN:

您不能覆盖​​非虚或
  静态方法。在重写的基
  方法必须是虚拟的,抽象的,或
  覆盖。

You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

因此​​,需要'新'的关键字,让您可以覆盖非虚拟和静态方法。

So the 'new' keyword is needed to allow you to 'override' non-virtual and static methods.

这篇关于在方法签名的新关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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