简体   繁体   English

C#列出IList或IEnumerable作为参数

[英]C# List IList or IEnumerable as argument

If I want to take a List as an argument of a method, Resharper gives a hint that using the IList interface might be a better idea. 如果我想将List作为方法的参数,Resharper会提示使用IList接口可能是一个更好的主意。 If I then replace List with IList, Resharper suggests IEnumerable. 如果我然后用IList替换List,Resharper建议使用IEnumerable。 In Java I would also take the List interface and not ArrayList as an argument. 在Java中,我还将List接口而不是ArrayList作为参数。 But is it really good looking code to use iEnumerable as an argument? 但是使用iEnumerable作为参数是否真的很好看? Is this good practice to use IEnumerable if no functionality of IList or List are required? 如果不需要IList或List的功能,这是使用IEnumerable的好习惯吗?

Here is the article that made me change my mind about all that and made me start following the principle of 这篇文章让我改变了主意,让我开始遵循原则

take the most generic type, return the most specific type 采用最通用的类​​型,返回最具体的类型

So to answer your question 所以回答你的问题

Is this good practice to use IEnumerable if no functionality of IList or List are required? 如果不需要IList或List的功能,这是使用IEnumerable的好习惯吗?

yes, it is 是的

note: do not over do it ! 注意:不要过度了! I've seen code that accepted an IEnumerable , then threw an exception if the parameter wasn't a List . 我已经看到接受IEnumerable代码,如果参数不是List则抛出异常。 This is stupid. 这是愚蠢的。 What the sentence I quoted above means is "don't ask for more specificity than you need" 我上面引用的句子意思是“不要求比你需要更多的特异性”

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

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