简体   繁体   English

c#对象实例化

[英]c# object instantiation

What's the difference between: 有什么区别:

Object o = new Object();
o.foo();

and

new Object().foo();

(assuming I do not need the reference afterwards) ? (假设我之后不需要参考)?

Are there any reasons for using one instead of the other one (eg memory usage) ? 是否有任何理由使用一个而不是另一个(例如内存使用)?

There's no difference in terms of execution. 执行方面没有区别。

There can be a difference in terms of debugging: 调试方面可能有所不同:

  • It can be handy to break after the object has been created but before foo() is called 在创建对象之后但在调用foo()之前,它可以很方便地中断
  • It can be handy to be able to inspect the value of the variable afterwards 之后能够检查变量的值是很方便的
  • If an exception is thrown, separating calls into multiple lines can make the source clearer. 如果抛出异常,将调用分成多行可以使源更清晰。 (I don't think it would be a problem in this particular case, but for NullReferenceException s in particular, it can be tricky if there are multiple dereferencing operations in the same statement). (我不认为在这种特殊情况下会出现问题,但特别是对于NullReferenceException ,如果同一语句中有多个解除引用操作,则可能会很棘手)。

I'm definitely not saying that you should always split everything out - just that it can be useful for debugging purposes. 我绝对不是说你应该总是将所有内容分开 - 只是它可以用于调试目的。

如果之后不需要实例,则没有区别。

If you don't need o afterwords then there is no difference. 如果你不需要o后语,那么没有区别。
The (JIT) compiler will probably treat them as being the same. (JIT)编译器可能会将它们视为相同。

So it's a matter of taste. 所以这是一个品味问题。 In this case I have a slight preference for the first one, but sometimes the fluent notation of the second sample is more readable. 在这种情况下,我略微偏爱第一个,但有时第二个样本的流畅表示法更具可读性。

No difference. 没有不同。

To probe it, you can compile both codes (release mode), inspect them with ildasm and you will see the resulting bytecode witll be the same. 要探测它,你可以编译两个代码(发布模式),用ildasm检查它们,你会看到结果字节码是相同的。

EDIT: actually, I sometimes find it easier to debug when the variable is declared. 编辑:实际上,我有时发现在声明变量时更容易调试。 Easier to inspect, so, easier to debug. 更容易检查,因此更容易调试。

EDIT: Removed incorrect code 编辑:删除了错误的代码

The difference is that in the first case you can see the object being created in the debugger. 不同之处在于,在第一种情况下,您可以看到在调试器中创建的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM