我创建了以下扩展方法:
<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
,并显示消息Object variable or With block variable not set.
是否有一种安全的方法以这种方式对会话变量使用扩展方法(假设会话变量可能为null)?
答案 0 :(得分:1)
无法对object
类型使用扩展方法(它应该是另一种类型)VB.NET: impossible to use Extension method on System.Object instance。
必须导入包含扩展方法的模块,以便您可以使用:
ReadOnly Property NodeID As Integer
Get
Return ToIntegerOrDefaultSession(SessionVariables.SELECTED_NODE_ID))
End Get
End Property
或者,您可以重写扩展方法
<System.Runtime.CompilerServices.Extension()> _
Public Function ToIntegerOrDefault(Sess As HttpSessionState, KeyOFvalueToParse As String, Optional ByVal defaultValue As Integer = 0) As Integer
Dim retVal As Integer = 0
If Not Integer.TryParse(Sess(KeyOFvalueToParse).ToString, retVal) Then
retVal = defaultValue
End If
Return retVal
End Function
并致电
Session.ToIntegerOrDefault(SessionVariables.SELECTED_NODE_ID)
或者为String
定义扩展方法并调用
Cstr(Session(SessionVariables.SELECTED_NODE_ID)).ToIntegerOrDefault()
答案 1 :(得分:0)
声明会话时为会话提供默认值。如果是使用new关键字的列表就可以了。如果它是其他东西,你将不得不展示它是什么。