使用 Nullable<value> 类型进行条件运算符赋值?
-
09-06-2019 - |
题
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
我经常发现自己想做这样的事情(EmployeeNumber
是一个 Nullable<int>
因为它是 LINQ-to-SQL dbml 对象上的属性,其中列允许 NULL 值)。不幸的是,编译器认为“‘null’和‘int’之间没有隐式转换”,尽管这两种类型在对可空 int 的赋值操作中都是有效的。
据我所知,空合并运算符不是一个选项,因为如果 .Text 字符串不为空,则需要在该字符串上进行内联转换。
据我所知,执行此操作的唯一方法是使用 if 语句和/或分两步分配它。在这种特殊情况下,我发现这非常令人沮丧,因为我想使用对象初始值设定项语法,并且此分配将在初始化块中......
有人知道更优雅的解决方案吗?
解决方案
出现问题的原因是条件运算符不考虑如何使用值(在本例中是分配的)来确定表达式的类型 - 只考虑真/假值。在这种情况下,你有一个 无效的 和 整数32, ,并且类型无法确定(有真正的原因它不能只是假设 可空<Int32>).
如果您确实想以这种方式使用它,则必须将其中一个值转换为 可空<Int32> 你自己,所以 C# 可以解析类型:
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? (int?)null
: Convert.ToInt32(employeeNumberTextBox.Text),
或者
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text),
其他提示
我认为实用方法可以帮助使这个更干净。
public static class Convert
{
public static T? To<T>(string value, Converter<string, T> converter) where T: struct
{
return string.IsNullOrEmpty(value) ? null : (T?)converter(value);
}
}
然后
EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);
虽然亚历克斯为你的问题提供了正确且最接近的答案,但我更喜欢使用 TryParse
:
int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
? (int?)value
: null;
它更安全,可以处理无效输入以及空字符串的情况。否则,如果用户输入类似的内容 1b
他们将看到一个错误页面,其中包含未处理的异常 Convert.ToInt32(string)
.
您可以转换 Convert 的输出:
EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text)
//Some operation to populate Posid.I am not interested in zero or null
int? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;
var x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;
编辑:上面的简要解释,我试图获取的值 Posid
(如果它非空 int
并且在 varibale 中具有大于 0 的值 X1
. 。我不得不使用 (int?)
在 Posid.Value
使条件运算符不引发任何编译错误。仅供参考 GetHolidayCount
是一个 WCF
可以给出的方法 null
或任何数字。希望有帮助