質問

Possible Duplicate:
Bug?? If you assign a value to a nullable integer via a ternary operator, it can't become null

While this question may seem like a duplicate of many, it is actually being asked for a specific reason. Take this code, for example:

Dim n As Integer? = If(True, Nothing, 1)

In that code, the ternary expression should be returning Nothing, but it's setting n to 0. If this were C#, I could say default(int?) and it would work perfectly. Now it looks like I am going to have to ditch the ternary and use a regular If block, but I really want to use the ternary.

If Nothing were truly VB.NET's equivalent to C#'s default, how can you explain this behavior?

役に立ちましたか?

解決

The VB.NET equivalent to C#'s default is the keyword Nothing. The code you wrote should compile just fine so long as Id.Value returns an Integer value.

The reason your updated sample is going wrong is because of the nature of Nothing. In VB.NET Nothing is the empty value and it's convertible to any type. Now for an If expression, the compiler has to infer what the type of the return should be, and it does this by looking at the two value arguments.

The value Nothing has no type, but the literal 1 has the type Integer. Nothing is convertible to Integer so the compiler determines Integer is the best type here. This means when Nothing is chosen as the value, it will be interpreted as Integer and not Integer?.

The easiest way to fix this is to explicitly tell the compiler that you want 1 to be treated as an Integer?.

Dim n As Integer? = If(True, Nothing, CType(1, Integer?))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top