Checking if an object is a number in C#

前端 未结 11 1587
粉色の甜心
粉色の甜心 2020-11-29 19:35

I\'d like to check if an object is a number so that .ToString() would result in a string containing digits and +,-,.

11条回答
  •  感动是毒
    2020-11-29 20:24

    You could use code like this:

    if (n is IConvertible)
      return ((IConvertible) n).ToDouble(CultureInfo.CurrentCulture);
    else
      // Cannot be converted.
    

    If your object is an Int32, Single, Double etc. it will perform the conversion. Also, a string implements IConvertible but if the string isn't convertible to a double then a FormatException will be thrown.

提交回复
热议问题