Is there a VB.NET expression that *always* yields null?

后端 未结 4 1757
走了就别回头了
走了就别回头了 2021-02-19 19:18

We all know that VB\'s Nothing is similar, but not equivalent, to C#\'s null. (If you are not aware of that, have a look at this answer first.)

4条回答
  •  囚心锁ツ
    2021-02-19 19:39

    The first answer I gave missed some points, but this should do it:

    Dim o As Object = If(myBool, 5, DirectCast(Nullable.GetUnderlyingType(GetType(Integer)), Object))
    

    This uses the fact that Nullable.GetUnderlyingType will return a null reference if you pass it a type which isn't a nullable value type - which Integer isn't. Other alternatives exist, such as Type.GetElementType(), or perhaps GetType(Object).BaseType.

    I've checked that this works with multiple different types for the second operand.

    It's slightly annoying that you have to cast to Object... I'm still working on alternatives for that...

提交回复
热议问题