我创建了以下扩展方法:
<System.Runtime.CompilerServices.Extension()> _
Public Function ToIntegerOrDefault(ByVal valueToParse As Object, Optional ByVal defaultValue As Integer = 0) As Integer
Dim retVal As Integer = 0
If Not Integer.TryParse(valueToParse.ToString, retVal) Then
retVal = defaultValue
End If
Return retVal
End Function
我想在会话变量上使用这个扩展方法,如下所示:
ReadOnly Property NodeID As Integer
Get
Return Session(SessionVariables.SELECTED_NODE_ID).ToIntegerOrDefault()
End Get
End Property
但是,在设置会话变量之前调用该方法时,NullReferenceException
会抛出带有消息的 aObject variable or With block variable not set.
有没有一种安全的方法可以以这种方式在会话变量上使用扩展方法(假设会话变量可能为空)?