为什么IEnumerable <t>在这里返回null?</t>

时间:2012-08-11 20:37:49

标签: c#

任何人都可以告诉我为什么方法参数IEnumerable返回null,即使它是在callee方法中分配的。 我们都知道interface是一个引用类型。

不要考虑逻辑。我刚刚更换了我的业务逻辑以适应场景

static void Main()  
{   
  IEnumerable<int> gEnumerable = null;  
  Foo(gEnumerable);    //here param gEnumerable always returns null even if i assign  value at my Foo(), why is it so???  
}    

static IEnumerable<int> Bar(List<int> lst)         
{  
  return lst.Select(k => k);  
}  

private  static  void Foo(IEnumerable<int> response)  
{  
  response = Bar(new List<int> { 1, 2, 3, 4, 5, 6 });  
}

请向我解释一下这个

3 个答案:

答案 0 :(得分:4)

  

我们都知道interface是一种引用类型。

你需要研究一下如何在C#中传递参数。 Everything 按值传递(默认情况下)。在引用类型的情况下,传递给函数时引用复制(因为引用是其值)。因此,您要为引用的副本分配新值,并且调用者不会看到它。

如果您确实需要为引用分配全新值,则必须使用refout说明符。如果您的方法保证它将为其输入分配新值,则使用out

答案 1 :(得分:3)

您必须通过引用传递response,否则您不会更改传递的原始引用 - 如果可以避免,则应避免使用此方法:

static void Main()  
{   
  IEnumerable<int> gEnumerable = null;  
  Foo(ref gEnumerable);    
} 
private  static void Foo(ref IEnumerable<int> response)  
{  
   response = Bar(new List<int> { 1, 2, 3, 4, 5, 6 });  
}

为什么不重新设计并让Foo返回您想要的值?那是更清洁的imo。

private  static IEnumerable<int> Foo()  
{  
   return Bar(new List<int> { 1, 2, 3, 4, 5, 6 });  
}

答案 2 :(得分:2)

您需要使用Ref关键字传递参数,以便修改gEnumerable而不是创建新的枚举,这些枚举将在它们离开作用域后立即处理。

static void Main()  
{   
  IEnumerable<int> gEnumerable = null;  
  Foo(ref gEnumerable);    //here param gEnumerable always returns null even if i assign       value at my Foo(), why is it so???  
}    

static IEnumerable`<int>` Bar(List`<int>` lst)         
{  
   return lst.Select(k => k);  
}  

private  static  void Foo(ref IEnumerable`<int>` response)  
{  
  response = Bar(new List`<int>` { 1, 2, 3, 4, 5, 6 });  
}
相关问题