鉴于以下设置和代码片段,您可以提出使用其中一个的原因是什么?我使用其中任何一个都有几个论点,但我很好奇其他人的想法.
建立
public class Foo
{
public void Bar()
{
}
}
Run Code Online (Sandbox Code Playgroud)
Snippet One
var foo = new Foo();
foo.Bar();
Run Code Online (Sandbox Code Playgroud)
小片二
new Foo().Bar();
Run Code Online (Sandbox Code Playgroud)
第一个版本意味着您可以foo在调用之前更轻松地在调试器中进行检查Bar().
第一个版本还意味着您将一个名称与该对象相关联(实际上它实际上是变量的名称,但显然存在心理关联),它有时会很有用:
var customersWithBadDebt = (some big long expression)
customersWithBadDebt.HitWithBaseballBat();
Run Code Online (Sandbox Code Playgroud)
比...更清楚
(some big long expression).HitWithBaseballBat();
Run Code Online (Sandbox Code Playgroud)
如果这些原因都不适用,请随意选择单行版本.这是个人品味,然后应用于每个特定的背景.