聚合以及如何检查是否可以对对象求和

geo*_*yan 6 .net c# interface aggregation

我需要写一些我称之为Aggregation Container的东西,它存储Aggregations,它本质上是一个Action,它接收一组对象并输出一个对象作为结果.聚合的例子是:算术平均值,一组数字的中位数,调和平均值等.这是一个示例代码.

var arithmeticMean = new Aggregation
        {
            Descriptor = new AggregationDescriptor { Name = "Arithmetic Mean" },
            Action = (IEnumerable arg) =>
            {
                double count = 0;
                double sum = 0;

                foreach (var item in arg)
                {
                    sum += (double)item;
                    count++;
                }

                return sum / count;
            }
        };
Run Code Online (Sandbox Code Playgroud)

这是我的代码问题.我假设对象只是两倍,因此进行了转换.如果他们不加倍怎么办?我怎样才能确保我可以将两个对象相加?在标准的.Net程序集中是否有某种接口?我需要像ISummable这样的东西...或者我需要自己实现它(然后我将必须包装所有原始类型,如double,int,etcetera来支持它).

有关此类功能设计的任何建议都会有所帮助.

Ser*_*kiy 3

看一下Enumerable类方法 - 它有一组根据它支持的每种类型进行参数化的方法:

int Sum(this IEnumerable<int> source)
double Sum(this IEnumerable<double> source)
decimal Sum(this IEnumerable<decimal> source)
long Sum(this IEnumerable<long> source)
int? Sum(this IEnumerable<int?> source)
// etc
Run Code Online (Sandbox Code Playgroud)

这是使方法参数“可求和”的唯一方法。

不幸的是,您无法使用泛型类型参数约束创建一些泛型方法,这将仅允许带有 + 运算符重载的类型。.NET 中的运算符没有任何限制,运算符也不能成为某些接口的一部分(因此它们是静态的)。因此,不能将运算符与泛型类型的变量一起使用。

另外,如果您查看 .NET 基元类型定义,您将找不到任何可以帮助您的接口 - 仅实现了比较、格式化和转换:

public struct Int32 : IComparable, IFormattable, IConvertible, 
                      IComparable<int>, IEquatable<int>
Run Code Online (Sandbox Code Playgroud)