简体   繁体   English

C#中对象实例化之间的区别:将对象存储在引用中与直接调用方法

[英]Diferences between object instantiation in C#: storing objects in references vs. calling a method directly

I have a doubt with the objects declarations in c#. 我对C#中的对象声明有疑问。 I explain with this example I can do this: 我用这个例子解释我可以做到这一点:

MyObject obj = New MyObject(); 
int a = obj.getInt();

Or I can do this 或者我可以做到这一点

int a = new MyObject().getInt();

The result are the same, but, exists any diferences between this declarations? 结果是相同的,但是这些声明之间是否存在任何区别? (without the syntax) (没有语法)

Thanks. 谢谢。

This isn't a declararation: it's a class instantiation. 这不是声明:它是类实例化。

There's no practical difference: it's all about readability and your own coding style. 两者之间没有实际的区别:都是关于可读性和您自己的编码风格的。

I would add that there're few cases where you will need to declare reference to some object: when these objects are IDisposable . 我要补充一点,在少数情况下,您需要声明对某个对象的引用:这些对象是IDisposable

For example: 例如:

// WRONG! Underlying stream may still be locked after reading to the end....
new StreamReader(...).ReadToEnd(); 

// OK! Store the whole instance in a reference so you can dispose it when you 
// don't need it anymore.
using(StreamReader r = new StreamReader(...))
{

} // This will call r.Dispose() automatically

As some comment has added, there're a lot of edge cases where instantiating a class and storing the object in a reference (a variable) will be better/optimal, but about your simple sample, I believe the difference isn't enough and it's still a coding style/readability issue . 正如一些评论所补充的,在很多情况下,实例化一个类并将对象存储在引用(变量)中将是更好/最优的, 但是对于您的简单示例,我相信差异还不够,并且仍然是编码风格/可读性的问题

It's mostly syntax. 主要是语法。

The main difference is that you can't use the instance of MyObject in the second example. 主要区别在于您不能在第二个示例中使用MyObject实例。 Also, it may be nominated for Garbage Collection immediately. 另外,它可能会立即被提名垃圾收集。

No, technically they are the same. 不,从技术上讲,它们是相同的。

The only thing I would suggest to consider in this case, as if the function does not actual need of instance creation, you may consider declare it static, so you can simply call it like: 在这种情况下,我建议考虑的唯一事情是,好像该函数实际上不需要实例创建一样,您可以考虑将其声明为静态,因此可以像下面这样简单地调用它:

int a = MyObject.getInt();

but this naturally depends on concrete implementation. 但这自然取决于具体的实现。

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

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