除非您使用On Error Resume Next
并且构造函数中存在异常MyClass
,或者您创建了一个在创建时返回的代理Nothing
。
在确认代理的 VB.NET 版本“有效”时,我注意到myObj Is Nothing
它是False
在创建之后立即发生的(就像您在 OP 中要求的那样),但是当您尝试用它做任何其他事情时,它肯定看起来像Nothing
. Nothing
一旦你尝试用它做更多而不是测试它的价值,它通常会变成。(在这个阶段它与 C# 相同。在这一点上我真的应该开始一个新问题......)
但我发现“空”的存在Try Catch
足以让 VB.NET 将Nothing
! (从 LinqPad 的 Roslyn C# 6 (Beta) 版本开始,C# 的性能相同。)
Sub Main()
Dim myObj = New MyFunnyType()
If myObj Is Nothing Then
Call "It IS Nothing".Dump
Else
' Comment out this Try and myObj will not be Nothing below.
Try
'Call myObj.ToString.Dump
Catch nr As NullReferenceException
Call "Maybe it was nothing?".Dump
Catch ex As Exception
Call ex.Message.Dump
End Try
Call myObj.Dump("Nil?")
If myObj Is Nothing Then
Call "Now it IS Nothing".Dump
Else
Call "It still is NOT Nothing!".Dump
End If
End If
End Sub
' Define other methods and classes here
Class MyFunnyProxyAttribute
Inherits ProxyAttribute
Public Overrides Function CreateInstance(ByVal ServerType As Type) As MarshalByRefObject
Return Nothing
End Function
End Class
<MyFunnyProxy> _
Class MyFunnyType
Inherits ContextBoundObject
Public Overrides Function ToString() As String
If Me IsNot Nothing Then
Return "Yes, I'm here!"
Else
Return "No, I'm really Nothing!"
End If
End Function
End Class
请注意,调用ToString
是要被注释掉的:当它不是时,它Nothing
被结晶为“预期的”。
(在基于 Roslyn C# 6 的 LinqPad 之前,我在 C# 中没有看到类似的效果。即仅在 中注释掉ToString
调用try
就足以myObj
保持非null
.C# 6 LinqPad(Beta)的性能与 VB.NET 相同, 要求try
将 去除以不null
结晶。)