可空&LT条件运算符分配;价值>类型? [英] Conditional operator assignment with Nullable<value> types?

查看:158
本文介绍了可空&LT条件运算符分配;价值>类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我经常发现自己想要做这样的事情( EmployeeNumber 可空< INT> ,因为它是一个物业的LINQ到SQL的dbml对象,其中列允许使用NULL值)上。不幸的是,编译器认为,有'空'和'廉政'之间不存在隐式转换,尽管这两种类型将是一个赋值操作有效靠自己一个可空int类型。

I often find myself wanting to do things like this (EmployeeNumber is a Nullable<int> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that "There is no implicit conversion between 'null' and 'int'", even though both types would be valid in an assignment operation to a nullable int on their own.

空合并运算符是不是一种选择,因为据我可以看到,因为需要的。文本字符串发生,如果它不是空的内联转换。

Null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the .Text string if it's not null.

据我知道做到这一点的唯一方法是如果使用的语句和/或分两步进行分配。在这种特殊情况下我觉得很沮丧,因为我想用对象初始化语法和这项任务将在初始化块...

As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...

任何人都知道一个更优雅的解决方案?

Anyone know a more elegant solution?

推荐答案

出现问题的原因条件运算符不看如何使用值(分配在这种情况下),以确定前$ P $的类型pssion - 只是真/假值。在这种情况下,你有一个的的和的的Int32 ,类型不能确定(有真正的原因,它不能只是假定的可空&LT;的Int32&GT ;

The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a null and an Int32, and the type can not be determined (there are real reasons it can't just assume Nullable<Int32>).

如果你真的想以这种方式来使用它,你必须转换值之一为可空&LT;的Int32&GT; 自己,所以C#能够解决的类型:

If you really want to use it in this way, you must cast one of the values to Nullable<Int32> yourself, so C# can resolve the type:

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

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

这篇关于可空&LT条件运算符分配;价值&GT;类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆