如果值为 null 或为空,则转换为 double 失败

Tar*_*uki -2 c#

我写了一个将字符串转换为double的方法,这是代码

public double convertToDouble(string number)
{
    string temp = number;
    if (number.Contains("x"))
    {
        int locationE = number.IndexOf("x");
        string exponent = number.Substring(locationE + 5, number.Length - (locationE + 5));
        temp = number.Substring(0, locationE - 1) + "E" + exponent;
    }

    return Convert.ToDouble(temp);
}
Run Code Online (Sandbox Code Playgroud)

但是如果临时变量作为 null 或空字符串传入,则转换将失败。我怎么能写这部分。

Chr*_*tos 5

为什么要为此目的编写新方法,而您可以使用更安全的方法,double.TryParse.

double number;

// The numberStr is the string you want to parse
if(double.TryParse(numberStr, out number))
{
    // The parsing succeeded.
}
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢上述方法并且想坚持使用您的方法,那么我看到的唯一选择就是抛出异常。

public double convertToDouble(string number)
{
    if(string.IsNullOrWhiteSpace(number))
    {
        throw new ArgumentException("The input cannot be null, empty string or consisted only of of white space characters", "number");
    }

    string temp = number;
    if (number.Contains("x"))
    {
        int locationE = number.IndexOf("x");
        string exponent = number.Substring(locationE + 5, number.Length - (locationE + 5));
        temp = number.Substring(0, locationE - 1) + "E" + exponent;
    }
    return Convert.ToDouble(temp);
}
Run Code Online (Sandbox Code Playgroud)