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

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

问题描述

在执行重构时,我最终创建了一个如下例所示的方法.为简单起见,数据类型已更改.

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

我以前有一个这样的赋值语句:

I previous had an assignment statement like this:

MyObject myVar = new MyObject();

它被意外重构为:

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

这是我的剪切/粘贴错误的结果,但是 private static new 中的 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.

问题:new 关键字在方法签名中表示什么?我假设它是 C# 3.0 中引入的东西?

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

这与 override 有何不同?

推荐答案

来自 MSDN 的新关键字参考:

New keyword reference from MSDN:

MSDN 参考

这是我在网上从 Microsoft MVP 中找到的一个很有意义的示例:原始链接

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.

因此需要new"关键字来允许您覆盖"非虚拟和静态方法.

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

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

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