是否可以使用条件运算符将值分配给可空值?
我知道我可以做到这一点:
Int32 tempInt;
Int32? exitNum;
if (Int32.TryParse(fields[13], out tempInt))
exitNum = tempInt;
else
exitNum = null;
但为什么我不能这样做呢?
Int32 tempInt;
Int32? exitNum = Int32.TryParse(fields[13], out tempInt) ? tempInt : null;
有没有办法使用条件运算符将值分配给可空值?
I know I can do this:
Int32 tempInt;
Int32? exitNum;
if (Int32.TryParse(fields[13], out tempInt))
exitNum = tempInt;
else
exitNum = null;
But why can't I do this?
Int32 tempInt;
Int32? exitNum = Int32.TryParse(fields[13], out tempInt) ? tempInt : null;
Is there a way to assign a value to a nullable using the conditional operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
条件运算符的一侧必须可转换为另一侧的类型。
就您而言,一侧有一个
int
,另一侧有null
(无类型表达式)。由于双方都不直接兼容另一方,因此它不起作用。您需要通过强制转换或编写
new int?()
来确保至少一侧是int?
。写入 Int32.TryParse(fields[13], out tempInt) ? tempInt : 新的 int?()
One side of the conditional operator must be convertible to the type of the other side.
In your case, you have an
int
on one side, andnull
(a type-less expression) on the other side. Since neither side is directly compatible with the other side, it doesn't work.You need to make sure that at least one side is an
int?
, either by casting, or by writingnew int?()
.Write
Int32.TryParse(fields[13], out tempInt) ? tempInt : new int?()
正如其他人所指出的,您必须确保条件运算符中存在一致的返回类型存在。 (C# 的一个微妙特征是,当我们必须在多个替代方案中为表达式生成一个类型时,所选择的替代方案始终位于表达式中的某个位置;我们绝不会“魔法化”一个不存在的类型。 )
如果您对有关条件运算符的不寻常事实感兴趣,我推荐我关于该主题的文章:
http://blogs.msdn.com/b/ericlippert/archive/tags/conditional+operator/
我想补充一点,这是编写扩展方法的绝佳机会:
现在您只能说
哪个读起来更愉快。
As others have noted, you have to insure that there is a consistent return type present in the conditional operator. (A subtle feature of C# is that when we must produce a type for an expression amongst several alternatives, the chosen alternative is always somewhere in the expression; we never "magic up" a type that didn't appear.)
If unusual facts about the conditional operator interest you, I recommend my articles on the subject:
http://blogs.msdn.com/b/ericlippert/archive/tags/conditional+operator/
I would add that this is a great opportunity to write an extension method:
And now you can just say
which is much more pleasant to read.
你只需要对 Int32 进行强制转换?临时值
You just need to do a cast to Int32? on tempInt
你可以将 null 转换为 int 吗?使双方具有相同的类型:
You can cast null to int? so that both sides have same type: