我应该使用IEnumerable之类的接口,还是List<>之类的具体类? [英] Should I use an interface like IEnumerable, or a concrete class like List<>
问题描述
我最近在其他地方表达了对此的看法*,但是我认为它值得进一步分析,因此我将其作为自己的问题发表.
I recently expressed my view about this elsewhere* , but I think it deserves further analysis so I'm posting this as its own question.
比方说,我需要在程序中创建并传递一个容器.至少在现阶段,我可能对一种容器与另一种容器没有强烈的看法,但我确实选择了一种.为了争辩,假设我要使用 List<> .
Let's say that I need to create and pass around a container in my program. I probably don't have a strong opinion about one kind of container versus another, at least at this stage, but I do pick one; for sake of argument, let's say I'm going to use a List<>.
问题是:编写我的方法来接受并返回诸如C#的 IEnumerable 之类的高级接口是否更好?还是应该编写方法来采用和传递我选择的特定容器类.
The question is: Is it better to write my methods to accept and return a high level interface such as C#'s IEnumerable? Or should I write methods to take and pass the specific container class that I have chosen.
我应该寻找哪些因素和标准来决定?哪种程序可以从一个程序中受益?计算机语言会影响您的决定吗?表现?程序大小?个人风格?
What factors and criteria should I look for to decide? What kind of programs work benefit from one or the other? Does the computer language affect your decision? Performance? Program size? Personal style?
(这有关系吗?)
**(作业:找到它.但是,在寻找自己的答案之前,请先在此处发布答案,以免造成偏见.)*
**(Homework: find it. But please post your answer here before you look for my own, so as not bias you.)*
推荐答案
您的方法应始终接受执行其功能所需的最不特定的类型.如果您的方法需要枚举,请接受IEnumerable
.如果它需要做特定于IList<>
的事情,那么根据定义,您必须给它一个IList<>
.
Your method should always accept the least-specific type it needs to execute its function. If your method needs to enumerate, accept IEnumerable
. If it needs to do IList<>
-specific things, by definition you must give it a IList<>
.
这篇关于我应该使用IEnumerable之类的接口,还是List<>之类的具体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!