我们什么时候需要使用" new"创建一个对象?什么时候我们可以宣布并为其分配价值?

时间:2014-06-03 13:19:44

标签: c#

更具体地说,在LINQ to Entities查询中:

List<string> myResult = (from myTable do some joins...blah).ToList();
if(myResuly.Any())
{
 // Foo
}

我的问题是我们如何知道我们是否可以使用

List<string> myResult = (from myTable do some joins...blah).ToList();

或者我们应该使用:

List<string> myResult = new List<string>();
 myResult = (from myTable do some joins...blah).ToList();

3 个答案:

答案 0 :(得分:2)

如果=右侧有一个生成值的功能,则您不需要new。在您的第3个示例中,您new的列表会立即被丢弃,而ToList()返回的列表将在其中使用

答案 1 :(得分:1)

我们应该从不使用(虽然它是 safe )这样的代码:

  List<string> myResult = new List<string>();
  myResult = ... // myResult is reassinged here and "new List<string>()" just lost

因为您只是在创建无用的 List<string>实例。换句话说

  List<string> myResult = WhatEver(...).ToList();

答案 2 :(得分:1)

如果您已经可以获得列表,为什么要浪费额外的代码?

List<string> myResult = new List<string>();

初始化列表的整个想法是,您还没有可以在'myResult'中存储的列表。

想象一下,尝试访问尚未初始化的列表。