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

kob*_*obe 7 c# expression if-statement

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

int? myInt=myTextBox.Text == "" ? null : 
    Convert.ToInt32(myTextBox.Text);
Run Code Online (Sandbox Code Playgroud)

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

以下作品:

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

如果我在整数中替换'null'(比如'4')它也有效:

int? myInt=myTextBox.Text == "" ? 4: 
    Convert.ToInt32(myTextBox.Text);
Run Code Online (Sandbox Code Playgroud)

Kun*_*han 7

试试这个:

int? myInt=myTextBox.Text == "" ? (int?)null : Convert.ToInt32(myTextBox.Text);
Run Code Online (Sandbox Code Playgroud)

  • 各位大家对int.TryParse hm :)都不太了解? (3认同)