我以前从未使用过泛型,想知道如何将类型限制为 Double[]
或 List<Double>
(或者如果这甚至是正确的事情)。我需要计算许多数字的平均值,这些数字有时是事先已知的(即我可以创建一个精确大小的数组),但在其他时候,这些数字是在计算之前立即生成的(即我使用列表)。
我想要这个通用方法 Average(T arrayOrList)
能够接受数组或列表而不是重载 Average()
方法。
谢谢!
最佳答案
因为两个double[]
和 List<double>
实现 IEnumerable<double>
,我建议如下:
public double Average(IEnumerable<double> arrayOrList) {
// use foreach to loop through arrayOrList and calculate the average
}
这是简单的子类型多态性,不需要泛型。
正如其他人已经提到的,如果您只想计算平均值,such a method already exists in the framework .
关于C# 泛型类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7028775/