【问题标题】:Calling an overload with null: casting vs default [closed]使用 null 调用重载:强制转换与默认值 [关闭]
【发布时间】:2012-09-19 00:49:27
【问题描述】:

不确定这是否是一个多余的问题,但考虑一下我有这些方法:

void Foo(SomeClass x)
{
    //Some code
}

void Foo(AnotherClass x)
{
    //Some code
}

假设我想用 null 调用特定的重载(SomeClass 之一),这是我的选择:

Foo((SomeClass)null)

Foo(null as SomeClass)

Foo(default(SomeClass))

基本上,哪个是最好的选择?不同方法之间是否存在显着的性能差异?一种特定的方式通常被认为比其他方式更“优雅”吗?

谢谢

【问题讨论】:

  • 它不会产生语义上的差异(我想知道有什么 IL 差异,如果有的话......)。始终如一。我总是使用前者,因为我喜欢 C# 中的“预先输入”。
  • 我认为您可能需要重新评估您在这里尝试做的事情。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# casting overloading default explicit


【解决方案1】:

选项 4:创建另一个重载:

void Foo()

使用需要强制转换的显式 null 调用?嗯……呜呜……

“正式”回答您的问题。试试看!

var sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++) {
    Foo(null as string);
}
Console.WriteLine(sw.ElapsedMilliseconds);

sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++) {
    Foo((string)null);
}           
Console.WriteLine(sw.ElapsedMilliseconds);

sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++) {
    Foo(default(string));
}
Console.WriteLine(sw.ElapsedMilliseconds);

Console.ReadLine();

我对所有 3 种方法都有大约 4 毫秒的时间。

在reflector中打开程序,看到所有的调用都变成了:Foo((string) null);

因此,您可以选择您认为最易读的任何内容。 IL 最终都完全相同。

【讨论】:

  • 不幸的是,重载 Foo() 已经存在,它使用另一个“默认”非空值调用 Foo(SomeClass x)。奇怪的方法,我知道,但它是我在这里使用的旧代码的一部分:P 感谢性能故障,看起来我将使用显式转换以保持一致性,因为它已经在其他地方使用了 :)
猜你喜欢
  • 2011-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
  • 2016-10-25
相关资源
最近更新 更多