三元运算符VB VS C#:为什么做出决议没有到零? [英] Ternary operator VB vs C#: why resolves Nothing to zero?

查看:168
本文介绍了三元运算符VB VS C#:为什么做出决议没有到零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只拍自己的脚,想知道是否有实际的原因使这种情况成为可能。结果
反正,这个问题可以留为将来脚射手的便利。

I just shoot myself in the foot and would like to know whether there were actual reasons to make this situation possible.
And anyway, this question can stay for the convenience of the future foot shooters.

假设我们有一个vb.net可空值:

Suppose we have a nullable value in vb.net:

Dim i as Integer?

我们希望一个值分配给它,立足的条件,并使用三元运算符,因为它是如此整洁的东西:

We want to assign a value to it, basing on a condition, and using a ternary operator, because it's so neat and stuff:

i = If(condition(), Nothing, 42)

也就是说,如果一个条件是真正,使用的为空,否则价值。结果
在该点处拍摄时发生。无明显原因的VB编译器决定,共同的基本类型没有整数整数,此时它默默的转换语句:

That is, if a condition is true, employ the nullability, otherwise the value.
At which point the shooting occurs. For no apparent reason VB compiler decides that the common base type for Nothing and Integer is Integer, at which point it silently translates the statement to:

i = If(condition(), 0, 42)


现在,如果你做到这一点在C#中:


Now, if you were to do this in C#:

i = (condition()) ? null : 42;

您马上会得到一个编译器错误,指出<零> INT 拌匀。这是伟大的,因为我的脚会一直健康已经我去了C#的方式这个时候。而对于这个编译,你必须明确地写:

You would immediately get a compiler error saying that <null> doesn't mix well with int. Which is great, as my foot would have been healthier had I went the C# way this time. And for this to compile, you have to explicitly write:

i = (condition()) ? null : (int?)42;


现在,您的可以的做同样的在VB,并得到正确的空内斯你所期望的:


Now, you can do the same in VB and get the correct null-ness you would expect:

i = If(condition(), Nothing, CType(42, Integer?))

但是,这要求其摆在首位你脚射门。有没有编译器错误,而且也没有警告。这是与明确在严明就

所以我的问题是,为什么?结果
我应该把这个作为一个编译错误?结果
或者有人可以解释为什么编译器就这样?

So my question is, why?
Should I take this as a complier bug?
Or can someone explain why the compiler behaves this way?

推荐答案

这是因为VB的没有不是直接等同于C#的

This is because VB's Nothing is not a direct equivalent to C#'s null.

例如,在C#这code将不能编译:

For example, in C# this code will not compile:

int i = null;

但是,这V​​B.Net code工作的很好:

But this VB.Net code works just fine:

Dim i As Integer = Nothing

VB.Net的没有实际上是C#的默认(T)前pression更匹配。

VB.Net's Nothing is actually a closer match for C#'s default(T) expression.

这篇关于三元运算符VB VS C#:为什么做出决议没有到零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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