2

我创建了以下扩展方法:

<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.

有没有一种安全的方法可以以这种方式在会话变量上使用扩展方法(假设会话变量可能为空)?

4

2 回答 2

1

不可能对一个object类型使用扩展方法(它应该是另一种类型)VB.NET:不可能在 System.Object 实例上使用扩展方法。必须导入具有扩展方法的模块,以便您可以使用:

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()
于 2013-05-29T21:26:47.030 回答
0

声明时给 Session 一个默认值。如果它是一个使用 new 关键字的列表就可以了。如果它是别的东西,你将不得不展示它是什么。

于 2013-05-29T19:19:23.493 回答