开发者

How to cast objects to double with minimum casting

Let suppose i have 5 objects and each开发者_JS百科 object contains double values.

I want to sum them up so that

double result=obj 1+obj 2+obj 3+obj 4+obj 5;

One way is to cast each object to double and then sum them up.

double result=(double)obj 1+(double)obj 2+(double)obj 3+(double)obj 4+(double)obj 5; //let suppose this cast works!

Is there any shorter way to do this?


You could put them into an array and use some LINQ onto it:

double sum = new[] { obj1, obj2, obj3, obj4 }.Cast<double>().Sum();

However, the best way would be keeping the doubles as doubles and don't put them into objects.


Cast, but with style...:

static double SumDoubleObjects(params Object[] objs)
    {
        double sum = 0;
        foreach (object curr in objs)
        {
            sum += (double)curr;
        }
        return sum;
    }

Possible upgrades:

  1. You could use extension method
  2. Add type safe checking

HTH

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜