相关疑难解决方法(0)

可空类型和三元运算符:为什么是`?10:null`禁止?

我刚刚遇到一个奇怪的错误:

private bool GetBoolValue()
{
    //Do some logic and return true or false
}
Run Code Online (Sandbox Code Playgroud)

然后,在另一种方法中,这样的事情:

int? x = GetBoolValue() ? 10 : null;
Run Code Online (Sandbox Code Playgroud)

很简单,如果方法返回true,则为Nullable intx 赋值10 .否则,将null赋给nullable int.但是,编译器抱怨:

错误1无法确定条件表达式的类型,因为int和之间没有隐式转换<null>.

我疯了吗?

.net c# nullable conditional-operator

242
推荐指数
6
解决办法
7万
查看次数

c#为什么不能将nullable int赋值为null

解释为什么无法为int赋值null,例如

int? accom = (accomStr == "noval" ? null  : Convert.ToInt32(accomStr));
Run Code Online (Sandbox Code Playgroud)

这段代码出了什么问题?

c# nullable

125
推荐指数
3
解决办法
12万
查看次数

标签 统计

c# ×2

nullable ×2

.net ×1

conditional-operator ×1