使用泛型获取C#中数组元素的总和 [英] Get sum of elements of an Array in C# using generics

查看:391
本文介绍了使用泛型获取C#中数组元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个方法,该方法可以采用数字类型的任意数组,并返回startIndex和endIndex之间的所有元素的总和.这就是我所拥有的:

I want to write a method which can take an arbitrary array of a numeric type and return the sum of all the elements between startIndex and endIndex. This is what I have:

private static T SumArrayRange<T>(T[] scores, int startIndex, int endIndex)
{
    T score = 0;
    for (int i = startIndex; i <= endIndex; i++)
    {
        score += scores[i];
    }
    return score;
}

但是编译失败并出现这2个错误.

But the compilation fails with these 2 errors.

  • 无法隐式转换类型'int' 到"T".
  • 运算符'+ ='不能为 应用于类型为"T"的操作数,并且 'T'
  • Cannot implicitly convert type 'int' to 'T'.
  • Operator '+=' cannot be applied to operands of type 'T' and 'T'

有什么办法可以迫使T只能是数字类型之一(long,double等)?还是他们解决这个问题的更优雅的方式?

Is there any way I can force T to be only one of the numeric types (long, double etc.)? Or is their a more elegant way of solving this?

推荐答案

不,没有办法限制通用类型参数使用运算符,并且也没有很好的解决方法.合适的接口是诸如INumericIArithmetic的接口,该接口具有诸如AddSubtract等的方法,并且由所有原始类型(例如intlong)实现.在MS中,有一个已有5年历史的功能请求连接,它仍然处于活动状态.关于该词的最新词是:

No, there's no way to constrain generic type parameters to use operators, and there are no good workarounds for that, either. A proper one would be an interface such as INumeric or IArithmetic with methods such as Add, Subtract etc, implemented by all primitive types such as int and long. There is a 5-year old feature request for that in MS Connect, which is still Active. The latest word on that is:

不幸的是,我们不得不削减计划以解决.NET Framework 4.0中的问题.

Unfortunately, we've had to cut our plans to solve this problem in the .NET Framework 4.0.

在此之前,您将被降级为:

Until then, you are relegated to either:

  • 自己使用反射-混乱且非常缓慢
  • 使用将为您使用Reflection的任何现有包装器(例如 Microsoft.VisualBasic.CompilerServices.Operators 类,使用AddObjectSubtractObject等方法,它们使用反射并为相应的运算符实现VB语义)-易于使用,但仍然很慢
  • 您要处理的
  • 硬编码类型(即,不支持用户定义类型上的重载算术运算符),并使用巨型if (x is int) ... else if (x is double) ...语句.
  • using Reflection yourself - messy and very slow
  • using any of the existing wrappers that will use Reflection for you (e.g. Microsoft.VisualBasic.CompilerServices.Operators class, with methods such as AddObject, SubtractObject etc which use reflection and implement VB semantics for the corresponding operators) - easy to use, but still very slow
  • hardcoding types you want to handle (i.e. no support for overloaded arithmetic operators on user-defined types), and using a giant if (x is int) ... else if (x is double) ... statement.

这篇关于使用泛型获取C#中数组元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆