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

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

    You can create one yourself (pick a different name for the function if you like):

    Private Function ValueOrNull(expression As Boolean, value As Object) As Object
      If expression Then Return value
      Return Nothing
    End Function
    

    Usage:

    Dim myBool As Boolean
    Dim o As Object = ValueOrNull(myBool, 5)
    

    Works with any type, including your example with 5.0.

提交回复
热议问题