Fastest Way for Converting an Object to Double?

前端 未结 5 1285
故里飘歌
故里飘歌 2021-01-01 17:32

What is the fastest way to convert an object to a double? I\'m at a piece of code right now, which reads:

var d = double.TryParse(o.ToString(), out d);  // o         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 17:43

    You must be doing a whole whopping lot of these in order to make any sense to spend any time on this. However, I am not here to judge:

    So, your code is this:

    if (o is IConvertible)
    {
        d = ((IConvertible)o).ToDouble(null);
    }
    else
    {
        d = 0d;
    }
    

    I wonder if you would be better off with this

    IConvertible convert = o as IConvertible;
    
    if (convert != null)
    {
      d = convert.ToDouble(null);
    }
    else
    {
      d = 0d;
    }
    

    Saves you the double cast.

提交回复
热议问题