接口向下转型
请假设我有以下扩展方法,以便能够强制评估 IEnumerable
:
public static List<T> EvaluateNow<T>(this IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
else
{
return (collection.ToList());
}
}
我想问一下是否有必要使用 IList
而不是 List
作为此方法的返回类型(即向下转换为接口),以便既不将其或其依赖项绑定到特定实现(即使返回值实际上始终是列表
)。
Please suppose I have the following extension method in order to be able to force evaluation of an IEnumerable
:
public static List<T> EvaluateNow<T>(this IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
else
{
return (collection.ToList());
}
}
I would like to ask if there is any point in having IList<T>
instead of List<T>
as this method's return type (i.e., downcasting to an interface) in order to tie neither it nor its dependencies to a particular implementation (even if the return value will always actually be a List
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下使用接口而不是类总是是一个好主意。
原因太多,无法在此一一赘述,但例如,它极大地提高了灵活性,因为任何类只需实现接口
IList
即可分配给该函数的返回值。类将实现此(或其他)接口,而无需子类化 List(或等效项)。一般来说,您希望使用符合要求的“最低”层次接口。在这种情况下,您可以考虑 ICollection,甚至 IEnumerable 而不是 IList。
从函数返回什么类实例并不重要,因为只返回“接口”,因此可以将其分配给实现该接口的任何类(再次,最大灵活性?)
通常会使用返回某些 IEnumerable 对象的函数在 foreach 循环内。
It is always a good idea to use interfaces in situations like this rather than classes.
The reasons why are too numerous to get into here, but for example, it greatly increass flexibility as any class just needs to implement the interface
IList<T>
to be assignable to the return value of this function. Classes will implement this (or other) interfaces without subclassing List (or equivalent).In general you want to use the 'lowest' heirachical interface that fits the requirements. In this case, you could consider ICollection, or even IEnumerable instead of IList.
It is irrelevant what class instance you return from the function, as only 'the interface' is returned, so it can be assigned to any class implementing that interface (again, max flexibilty?)
Often a function returning some IEnumerable object will mostly be used inside a foreach loop.
扩展方法只能在实例上调用。这意味着您的方法中的
collection
永远不能为null
。所以...正如所写,您的方法与扩展方法 IEnumerable.ToList 具有完全相同的行为,所以我没有看到任何意义。
如果它的返回类型是
IList
,就像 Aaron 在他的答案<中解释的那样,那将会很有用。 /a>.为什么
IEnumerable.ToList
尚未返回IList
对于库设计者来说是一个很好的问题。An extension method can only be called on an instance. Which means that
collection
can never benull
in your method.So... as written your method has the exact same behavior the extension method
IEnumerable.ToList
so I don't see any point.It would be useful if its return type was
IList
as Aaron explains in his answer.Why does
IEnumerable.ToList
not already return aIList
would be a good question for the library designers.