加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vb.net – 带Nothing检查的变量声明

发布时间:2020-12-17 07:20:10 所属栏目:百科 来源:网络整理
导读:非常(经常)我们需要写一些像 Dim Data = GetSomeData()If Data IsNot Nothing Then Data.DoSomething()Else ...End If 也许我是在徒劳地问,但我非常希望VB.Net有一些结构如下: IfExists Data = GetSomeData() Then Data.DoSomething()Else ...End IfExists
非常(经常)我们需要写一些像

Dim Data = GetSomeData()
If Data IsNot Nothing Then
  Data.DoSomething()
Else
  ...
End If

也许我是在徒劳地问,但我非常希望VB.Net有一些结构如下:

IfExists Data = GetSomeData() Then
  Data.DoSomething()
Else
  ...
End IfExists

在我的梦中,它做了两件重要的事情:

>没有额外的行没有检查
>变量A在块外不可见,因此以后不能错误地使用(就像“使用”或“使用”一样)

有什么类似于我还没有发现的东西吗?

谢谢!

编辑:
灵感来自Bj?rn-RogerKringsj?的答案,我想出了一些令我满意的东西(VB.Net的不足之处):

<Extension()>
Public Sub IfExists(Of T)(This As T,DoIfNotNothing As Action(Of T),Optional DoIfNothing As Action = Nothing)
    If This IsNot Nothing Then
        DoIfNotNothing(This)
    ElseIf DoIfNothing IsNot Nothing Then
        DoIfNothing()
    End If
End Sub

然后我可以像这样调用它(假部分是可选的)

GetSomeData().IfExists(Sub(Data) Data.DoSomething())

要么

GetSomeData().IfExists(Sub(Data) Data.DoSomething(),Sub() DoSomethingElse())

解决方法

正如其他人所说并且我暗示的那样,它无法完成.就像分享一个3’解决方案.这次我们将使用 delegates.

>没有额外的行没有检查
>变量A在块外部不可见,因此以后不能错误地使用.

履行

Public Module Extensions

    Public Sub IfExists(Of T)(testExpr As T,trueDlg As Action(Of T),falseDlg As Action)
        If (Not testExpr Is Nothing) Then
            trueDlg.DynamicInvoke(New Object(0) {testExpr})
        Else
            falseDlg.DynamicInvoke(New Object(-1) {})
        End If
    End Sub

End Module

用法

IfExists(GetSomeData(),Sub(A As Object)
             'We have something (A)
         End Sub,Sub()
             'We have nothing
         End Sub
    )

短:

IfExists(GetSomeData(),Sub(A As Object)
                                'We have something (A)
                            End Sub,Sub()
                                         'We have nothing
                                     End Sub)

或者,最短的版本:

IfExists(GetSomeData(),Sub(A As Object) Debug.WriteLine(A.ToString()),Sub() Debug.WriteLine("Nothing"))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读