如果允许输出为null,如何使用double.TryParse?

时间:2014-01-24 09:22:28

标签: c# nullable tryparse

在我的应用程序中,我有一个文本框 - txtDiscount,管理员可以为某个用户设置折扣百分比,或者他可能没有。在后端我想保存数据,所以现在我有这个:

double? discount = null;
if (!string.IsNullOrEmpty(txtDiscount.Text))
{
  if (!double.TryParse(txtDiscount.Text, out discount)) errors.Add("Discount must be a double.");
}

所以我收到invalid argument的错误,显然是discount,如果我要在TryParse中使用它,则无法为空。我看到很多人正在为这种情况做出扩展,但是现在我认为没有必要。我能想到的是使用另一个变量:

double? discount = null;
private double _discount;
if (!string.IsNullOrEmpty(txtDiscount.Text))
{
  if (!double.TryParse(txtDiscount.Text, out _discount)) 
  {
    errors.Add("Discount must be adouble.");
  }
  else
  {
    discount = _discount;
  }
}

然后使用我的可空discount将值传递给数据库。但实际上我不喜欢上面的代码,在我看来这个任务非常复杂,但我想不出更好的东西。那么如何在不使用扩展方法的情况下处理这种情况呢?

7 个答案:

答案 0 :(得分:4)

你可以不使用扩展方法进行解析 - 只需使用本地非可空值将其传递给TryParse方法:

double? discount = null;

if (!String.IsNullOrEmpty(txtDiscount.Text))
{   
   double value;
   if (Double.TryParse(txtDiscount.Text, out value))       
       discount = value;
   else       
       errors.Add("Discount must be a double."); // discount will have null value
}

但是我把所有这些逻辑都移到了扩展名上。

答案 1 :(得分:4)

您只需要使用本地非可空类型编写丑陋的代码,或者使用另一种方式来定义没有折扣。我同意可以为空的双重代表它是一种巧妙的方式,但如果代码惹恼了你,那么尝试不同的东西(bool,例如:discount_given = true)。

就个人而言,我只是使用扩展解析为可以为空的双倍:

    public static bool ParseDouble(string s, out double? dd)
    {
        double d;
        bool ret = double.TryParse(s, out d);

        if (ret)
            dd = d;
        else
            dd = null;

        return ret;
    }

答案 2 :(得分:1)

static void Main()
{
    var testStrings = new[] { "", "1.234" };

    foreach( var testString in testStrings )
    {
        double output;
        double? value = null;

        if( double.TryParse( testString, out output ) )
        {
            value = output;
        }

        Console.WriteLine( "{0}", value.HasValue ? value.Value.ToString() : "<null>" );
    }
}

答案 3 :(得分:0)

    public static double ToDouble(this string value, double fallbackValue = 0)
    {
        double result;

        return double.TryParse(value, out result) ? result : fallbackValue;
    }

答案 4 :(得分:0)

我知道这是一个老问题,但是在C#的新版本中,可以使用这种方式:

double? discount;
discount = (double.TryParse(myValueToParse, out double myParsedDouble) ? myParsedDouble : null);

通过这种方式,您尝试解析为局部变量myParseddouble。如果可能,将其分配为值,否则将其设置为null。

答案 5 :(得分:-1)

Nullable<double> discount = new Nullable<double>();

默认值已经为空,您不需要再将其设置为null

答案 6 :(得分:-1)

if(double.TryParse(txtDiscount.Text?? "", out _discount))
   discount=_discount;
else Console.WriteLine("Discount must be adouble.");