C# 通过方法返回 list<t> 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10557316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:19:56  来源:igfitidea点击:

What is the best way to return a list<t> via a method?

c#.netc#-4.0collections

提问by user1345632

Suppose I have a method that returns a list of String names.

假设我有一个返回字符串名称列表的方法。

public List<String> buildNamesList(){
   List<String> namesList = new List<String>();
   //add several names to the list
   return namesList;
}

Now if I have a method that needs that namesList would returning it like so be the best way?

现在,如果我有一个需要 namesList 的方法会像这样返回它是最好的方法吗?

public void someMethod(){
  List<String> namesList = new List<String>();
  namesList = buildNamesList();
  //traverse namesList
}

采纳答案by Ryan Lanciaux

If you are creating a new list in your buildNamesList method, I would just say:

如果您在 buildNamesList 方法中创建一个新列表,我只想说:

var namesList = buildNamesList(); 

回答by Oded

How to return the list really depends on what you are doing.

如何返回列表实际上取决于您在做什么。

If you simply need the whole list in memory, your approach is fine, though the way I would call it would be:

如果您只需要内存中的整个列表,那么您的方法很好,尽管我会这样称呼它:

public void someMethod(){
  List<String> namesList = buildNamesList();
}

There is no need to initialize the variable to an empty list that will get replaced immediately.

无需将变量初始化为将立即替换的空列表。

If the list is very large or you simply need to traverse it, you can use the yieldkeyword and change the return type of the function to IEnumerable<string>, though your current design doesn't fit this pattern.

如果列表非常大或者您只需要遍历它,您可以使用yield关键字并将函数的返回类型更改为IEnumerable<string>,尽管您当前的设计不适合这种模式。

回答by SLaks

Don't assign it your variable to new List<T>()only to immediately replace it with your return value.

不要将您的变量分配给它new List<T>()只是为了立即用您的返回值替换它。

回答by mattytommo

You don't need to initialise it twice, just do:

您不需要将其初始化两次,只需执行以下操作:

public void someMethod(){
    List<String> namesList = buildNamesList();
}

Although if you're an FxCop lover, strictly speaking it's not good practice to have methods return concrete types (Listin this instance), you should return the interface (IEnumerable)

尽管如果您是 FxCop 爱好者,严格来说让方法返回具体类型(List在本例中)并不是一个好习惯,您应该返回接口 ( IEnumerable)

Edit: For reference it's FxCop rule CA1059:)

编辑:作为参考,它是 FxCop 规则CA1059:)