三元运算符 VB 与 C#:为什么将 Nothing 解析为零? [英] Ternary operator VB vs C#: why resolves Nothing to zero?

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

问题描述

我只是朝自己的脚开枪,想知道是否有实际原因使这种情况成为可能.
无论如何,这个问题可以留下来方便未来的射手.

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 中有一个可以为 null 的值:

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)

也就是说,如果条件为 true,则使用可空性,否则使用值.
此时发生射击.没有明显的原因,VB 编译器决定 NothingInteger 的公共基类型是 Integer,此时它会默默地将语句转换为:

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?))

但这首先需要你的脚出手.没有编译器错误,也没有警告.这就是 Explicit OnStrict On.

But that requires having your foot shot in the first place. There's no compiler error and there's no warning. That's with Explicit On and Strict On.

所以我的问题是,为什么?
我应该将此视为编译器错误吗?
或者有人可以解释为什么编译器会这样?

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

推荐答案

这是因为 VB 的 Nothing 并不直接等同于 C# 的 null.

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

例如,在 C# 中,此代码将无法编译:

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

int i = null;

但是这个 VB.Net 代码工作得很好:

But this VB.Net code works just fine:

Dim i As Integer = Nothing

VB.Net 的 Nothing 实际上更接近 C# 的 default(T) 表达式.

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

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

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