使用null调用重载:强制转换为默认值

Pat*_*k M 2 c# casting default overloading explicit

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

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

void Foo(AnotherClass x)
{
    //Some code
}
Run Code Online (Sandbox Code Playgroud)

让我们说我想用null调用一个特定的重载(SomeClass一),这是我的选择:

Foo((SomeClass)null)

Foo(null as SomeClass)

Foo(default(SomeClass))
Run Code Online (Sandbox Code Playgroud)

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

谢谢

aqu*_*nas 5

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

void Foo()
Run Code Online (Sandbox Code Playgroud)

使用需要转换的显式null调用?嗯... ... EWW

要"正式"回答你的问题.试试吧!

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();
Run Code Online (Sandbox Code Playgroud)

所有3种方法都得到了~4ms.

当我在反射器中打开程序时,我看到所有的调用都变成了: Foo((string) null);

所以,你可以选择你认为最具可读性的东西.IL的结果完全相同.