有Nullable类型的条件运算符分配?

时间:2020-03-05 18:56:52  来源:igfitidea点击:
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),

我经常发现自己想做这样的事情(" EmployeeNumber"是一个" Nullable <int>",因为它是LINQ-to-SQL dbml对象的属性,其中该列允许使用NULL值)。不幸的是,即使这两种类型在对可空int的赋值操作中都是有效的,编译器仍认为"在'null'和'int'之间没有隐式转换"。

据我所知,Null合并运算符不是一个选项,因为如果不为null,则需要在.Text字符串上进行内联转换。

据我所知,唯一的方法是使用if语句和/或者分两步进行赋值。在这种特殊情况下,我感到非常沮丧,因为我想使用对象初始化器语法,并且此分配将在初始化块中...

有人知道更优雅的解决方案吗?

解决方案

回答

我们可以转换Convert的输出:

EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
   ? null
   : (int?)Convert.ToInt32(employeeNumberTextBox.Text)

回答

发生问题是因为条件运算符不会查看如何使用值(在这种情况下为赋值)来确定表达式的类型-只是true / false值。在这种情况下,我们有一个null和一个Int32,并且无法确定类型(确实有理由不能仅假设Nullable <Int32>)。

如果我们真的想以这种方式使用它,则必须自己将值之一强制转换为Nullable <Int32>,以便Ccan解析该类型:

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);

回答

尽管Alex为问题提供了正确的,最接近的答案,但我更喜欢使用TryParse

int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
    ? (int?)value
    : null;

这是更安全的方法,可以处理无效输入的情况以及空字符串情况。否则,如果用户输入类似" 1b"的内容,则会显示一个错误页面,其中包含在" Convert.ToInt32(string)"中引起的未处理的异常。