Ler*_*ica 6 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.");
}
Run Code Online (Sandbox Code Playgroud)
所以我得到了一个错误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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用我的nullable 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
}
Run Code Online (Sandbox Code Playgroud)
但是我把所有这些逻辑都移到了扩展上.
| 归档时间: |
|
| 查看次数: |
8971 次 |
| 最近记录: |