6

I am making a library which is going to be used widely by different applications. You can say that it is sort of a public library or SDK.

Currently I am working on a function which takes a list of Points performs some calculation on these points and then return list of updated points. So my question here is what should I use as return type and in my parameters. IList, IEnumerable or Collection.

So here it the function. I am unaware what user will do with the output. How user uses it, is on him. So what should be best option to use here.

public static IEnumerable<Point2D> PeformSomeCalculation(IEnumerable<Point2D> points)
{
    // Do something,
    return updatedPoints;
}
4

4 回答 4

1

IList<T>接口继承自ICollection<T>和。IEnumerable<T>IEnumerable

因此,如果您返回一个IList<T>,想要一个ICollection<T>、一个IEnumerable<T>或只是一个的客户IEnumerable都会很高兴。

于 2013-09-12T07:50:04.013 回答
1

你想操纵积分收集吗?

如果是这样,请使用ICollectionIList作为这些暴露AddClearRemove方法。

如果您需要对列表进行索引,那么您应该选择IList- 此接口继承自ICollectionIEnumerable因此这可能就是您所追求的。

如果您不需要修改或索引集合,请使用IEnumerable.

于 2013-09-12T07:51:21.783 回答
0

一般来说,我会尽量不假设用户会做什么,除非我试图强制执行一个规则,比如这个集合是只读的,所以我会使用最通用的类​​型。您也可以考虑实现一个迭代器,因为您正在接受一个列表并返回一个更新的列表。

使用yield return语句对您的客户来说可能很方便,允许他们使用 ForEach 功能。实施简单。

于 2013-09-12T08:09:47.033 回答
0

作为参数,您应该使用最具体的所需类型。这意味着如果您只需要 IEnumarable 的功能,则应该使用 IEnumarable,而不是 ICollection 或 IList。

作为返回类型,您应该使用最通用的类​​型,但您应该注意 ICollection 和 IList 类型。如果您在 Linq to SQL 中使用它 - 此函数具有方法 contains 但 Linq 无法将此类型的此函数转换为 SQL。

于 2013-09-12T07:56:07.630 回答