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

后端 未结 4 1759
走了就别回头了
走了就别回头了 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:37

    The simple answer is, no. There is no expression in VB.NET that only returns null. As you know, when the compiler parses a command using ternary operator, it infers the output type based on the two inputs. If one of the two inputs is Nothing, it must rely solely on the other parameter. Therefore, the "right" way to do it in VB.NET is to first cast the other parameter to Object, thereby forcing the output of the operation to be an Object:

    Dim o As Object = If(myBool, DirectCast(5, Object), Nothing)
    

    If, however, you really need an in-line expression which, itself, always evaluates to null, you could always do it by invoking a lambda expression, like this:

    Dim o As Object = If(myBool, 5.0, (Function() Nothing).Invoke())
    

    That syntax should work in any situation and would always result in Nothing rather than potentially resulting in default value.

提交回复
热议问题