C# 方法重载与接口参数
我只是好奇,以下示例被认为是“最佳实践”:我有一个数字数组或数字列表,并且希望将其提供给函数以返回平均值。
对于每种情况重载该方法是否更好:
double Average(int[] intArray){...}
double Average(uint[] uintArray){...}
double Average(double[] doubleArray){...}
...
double Average(List<int> intList){...}
...
或者,使用某种类型的接口是否更好:
double Average(IEnumerable arrayOrList)
{
// Branching logic for array or list.
}
谢谢!
编辑
平均值
用作示例。我有几种数值算法,需要能够在各种数值数据上运行。
I'm just curious, what is considered the "best practice" for the following example: I have either a numeric array or numeric list and want to supply it to a function to return the average.
Is it better to overload the method for each case:
double Average(int[] intArray){...}
double Average(uint[] uintArray){...}
double Average(double[] doubleArray){...}
...
double Average(List<int> intList){...}
...
Or, is it better to use some type of interface:
double Average(IEnumerable arrayOrList)
{
// Branching logic for array or list.
}
Thanks!
EDIT
Average
is used as an example. I have several numeric algorithms which need to be able to run on a variety of numeric data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 Enumerable.Average 扩展的各种重载指导方法:
这种风格的方法适用于任何实现 IEnumerable (T[]< /a>, 列表 、HashSet 、ReadOnlyCollection , ...) 并避免非泛型 IEnumerable 参数。由于 C# 没有
where T : num
约束,您需要为您希望支持的所有原始类型提供重载(Int32、Int64 ,单个,双,十进制,...)。Take a look at the various overloads of the Enumerable.Average Extension Method for guidance:
A method in this style works for any collection type that implements IEnumerable<T> (T[], List<T>, HashSet<T>, ReadOnlyCollection<T>, ...) and avoids the overhead incurred by a non-generic IEnumerable argument. Since C# doesn't have a
where T : num
constraint, you need to provide an overload for all primitive types you wish to support (Int32, Int64, Single, Double, Decimal, ...).接口将允许您提供数组或任何其他集合。不过,您可能希望使用强类型接口,例如
IEnumerable
。An interface will allow you to supply an array or any other collection. You might want to use a strongly typed interface like
IEnumerable<int>
though.假设
Average
只是一个示例,您应该使用 IEnumerable 但使用您的数据类型重载该函数,如下所示:IEnumerable
例如:
Assuming
Average
is just an example, you should use IEnumerable but overload the funciton with your data type, like so:IEnumerable<DataType>
For example: