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 在我的梦中,它做了两件重要的事情: >没有额外的行没有检查 有什么类似于我还没有发现的东西吗? 谢谢! 编辑: <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.
>没有额外的行没有检查 履行 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")) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |