创建新的对象最佳实践

本文关键字:最佳 对象 创建 | 更新日期: 2023-09-27 18:13:36

有时,为了简化代码,我在方法调用中实例化了一个新对象,而不是将新对象赋值给一个变量。做其中一种或另一种有什么缺点?

T myobj = new T();
elements.Add(myobj);

,和

elements.Add(new T());

创建新的对象最佳实践

以后需要引用

正如adaam在注释中提到的,如果您需要保留对对象的引用,因为您将使用它,那么最好这样做。

T myobj = new T();
elements.Add(myobj);
T.DoStuff(); //this might need to happen further down in the code, so keeping the reference is handy. Otherwise we'd have to dig it out of the elements. And you might be thinking "well, I don't need to reference it later in the code." But what if you're refactoring the code and it requires some modification? Now you'll need to change it, rather than having done it with a separate declaration in the first place.
<标题> 调试

一种常见的情况是当您使用调试器逐步执行代码时。很难看到以这种方式创建的对象的属性。

elements.Add(new T());

当给出自己的引用时,您可以轻松地使用IDE的调试工具来检查值,如果代码如下所示:

T myobj = new T();
elements.Add(myobj);
<标题> 可读性

选择其中一个而不是另一个的另一个原因是可读性。这是基于意见的,但是您应该询问与您一起工作的团队,以确定遵循哪种实践。问大家Stack Overflow哪个读起来更好是离题的。