我在C#中有一个类,我想实现在泛型数组中进行操作的方法.例如,我想从通用数组中获取最大组件值.在我的情况下,只考虑数字类型(int,long,double ......)就足够了
public class NumericCalculation<T> where T : IComparable<T>
{
public static T getMax (T[] array)
{
T maxValue = default(T);
if ( array.Length > 0) {
maxValue = array[0];
for (int i = 0; i < array.Length; i++) {
if (array[i] > maxValue)
{
maxValue = array[i];
}
}
}
return maxValue;
}
}
Run Code Online (Sandbox Code Playgroud)
但这会返回错误:"错误2运算符'>'不能应用于'T'和'T'类型的操作数"
有没有我正在跳过的界面?是否可以对通用数字数组执行此通用方法?
谢谢!
听起来你只是想要:
return array.DefaultIfEmpty().Max();
Run Code Online (Sandbox Code Playgroud)
但是要回答您的具体问题,您可以使用CompareTo,这是IComparable<T>您已将数组元素类型约束为的接口的成员:
if(array[i].CompareTo(maxValue) > 0) { ... }
Run Code Online (Sandbox Code Playgroud)
但就个人而言,我会使用Comparer<T>.Default它,因为它null更好地处理参考.在您的情况下,这并不重要,因为您只对原始数值类型(所有结构)感兴趣:
if(Comparer<T>.Default.Compare(array[i], maxValue) > 0) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |