开发者

Compute the sum of a sequence of object values inside a System.Array instance

I have this code:

private object Add(object a, object b)
{
    // Assume: a a开发者_如何学编程nd 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?
}

There are many alternative (and of course better) ways to do this using a regular array, generics or avoid passing object and just pass int, double, etc.

Just trying to figure out if this is possible at all (without the use of dynamic primitive type).


If you know that the array contains only ints, you can do that:

int sum = array.Cast<int>().Sum();

If the array contains integer numeric values, but you don't know their type, you can try something like that:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜