gpt4 book ai didi

c# - 允许输出为空时如何使用double.TryParse?

转载 作者:太空狗 更新时间:2023-10-29 21:50:21 32 4
gpt4 key购买 nike

在我的应用程序中,我有一个文本框 - 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;
}
}

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

最佳答案

您可以在没有扩展方法的情况下进行解析 - 只需使用本地不可空值将其传递给 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
}

但我已将所有这些逻辑移至扩展。

关于c# - 允许输出为空时如何使用double.TryParse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21328830/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com