Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算System.Array实例中对象值序列的总和_C#_Arrays - Fatal编程技术网

C# 计算System.Array实例中对象值序列的总和

C# 计算System.Array实例中对象值序列的总和,c#,arrays,C#,Arrays,我有以下代码: private object Add(object a, object b) { // Assume: a and b are the same types. // Assume: a and b are numeric types (ex. int). Array array = Array.CreateInstance(a.GetType(), 2); array.SetValue(a, 0); array.SetValue(b, 1

我有以下代码:

private object Add(object a, object b)
{
    // Assume: a and b are the same types.
    // Assume: a and b are numeric types (ex. int).

    Array array = Array.CreateInstance(a.GetType(), 2);
    array.SetValue(a, 0);
    array.SetValue(b, 1);

    // Is it possible to return the Sum of the values inside the Array instance?
}
使用常规数组、泛型或避免传递对象而只传递int、double等有许多替代方法(当然更好)


只是想弄清楚这是否可能(不使用动态基元类型)。

如果您知道数组只包含int,则可以执行以下操作:

int sum = array.Cast<int>().Sum();
int-sum=array.Cast().sum();
如果数组包含整数值,但您不知道它们的类型,可以尝试以下操作:

long sum = array.Cast<object>().Select(o => Convert.ToInt64(o)).Sum();
long sum=array.Cast().Select(o=>Convert.ToInt64(o)).sum();

如果类型为object,如何定义添加操作?编译器不会喜欢您试图添加两个“对象”,除非它能够推断如何添加它们。@Icarus这是真的。使用动态原语类型,它可以推断它。但似乎用其他方法是不可能的(泛型也会使你失败,但是C++模板工作得很好。如果有一个‘t实现xxx运算符泛型约束’,那就太好了……