c#short if语句不能与int一起使用? (INT = NULL)

时间:2012-11-11 10:25:04

标签: c# if-statement expression

我试图通过使用short-if来缩短我的代码:

int? myInt=myTextBox.Text == "" ? null : 
    Convert.ToInt32(myTextBox.Text);

但是我收到以下错误: 无法确定条件表达式的类型,因为''和'int'

之间没有隐式转换

以下作品:

int? myInt;
if (myTextBox.Text == "") //if no text in the box
   myInt=null;
else
   myInt=Convert.ToInt32(myTextBox.Text);

如果我用整数替换'null'(比如'4'),它也可以工作:

int? myInt=myTextBox.Text == "" ? 4: 
    Convert.ToInt32(myTextBox.Text);

5 个答案:

答案 0 :(得分:7)

请改为尝试:

int? myInt=myTextBox.Text == "" ? (int?)null : Convert.ToInt32(myTextBox.Text);

答案 1 :(得分:3)

我们需要的是让编译器知道if表达式的两个部分(if和else)是相同的。这就是为什么C#包含单词默认

int? myInt=myTextBox.Text == "" 
   ? default(int?)
   : Convert.ToInt32(myTextBox.Text);

答案 2 :(得分:1)

我的建议如下?

int value;
int? myInt = ( int.TryParse(myTextBox.Text, out value ) ) ? value : default(int?);

答案 3 :(得分:0)

int? myInt=myTextBox.Text == "" ? (int?)null : 
    Convert.ToInt32(myTextBox.Text);

答案 4 :(得分:0)

int number =!string.IsNullOrEmpty(temp) ? Convert.ToInt32(temp) : (int?) null;
相关问题