Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 在会话变量上使用扩展方法_Asp.net_Vb.net_Extension Methods_Session Variables - Fatal编程技术网

Asp.net 在会话变量上使用扩展方法

Asp.net 在会话变量上使用扩展方法,asp.net,vb.net,extension-methods,session-variables,Asp.net,Vb.net,Extension Methods,Session Variables,我创建了以下扩展方法: <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(valueToPar

我创建了以下扩展方法:

<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
但是,在设置会话变量之前调用该方法时,会抛出一个
NullReferenceException
,其中包含消息
对象变量或未设置块变量。


有没有一种安全的方法可以这样对会话变量使用扩展方法(假定会话变量可能为空)?

在声明会话时为会话指定一个默认值。如果是一个使用new关键字的列表,那么就可以了。如果是其他类型,则必须显示它是什么。

不可能对
对象使用扩展方法(它应该是另一种类型)。
必须导入具有扩展方法的模块,以便您可以使用:

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
或者为
字符串定义扩展方法并调用

Cstr(Session(SessionVariables.SELECTED_NODE_ID)).ToIntegerOrDefault()

如果你能提供一个如何做的例子,那就太好了。在OP没有说明集合是什么的情况下,你如何提供一个初始化集合的例子?我马上就能想出半打不同的收藏品。你好。扩展方法接受对象,尝试将其解析为整数,然后返回解析后的值(如果失败,则返回可选的默认值)。没有集合。您的代码看起来很好,会话上的密钥有效吗?我会先检查值是否为null。回答非常好,非常全面。非常感谢。
Session.ToIntegerOrDefault(SessionVariables.SELECTED_NODE_ID)
Cstr(Session(SessionVariables.SELECTED_NODE_ID)).ToIntegerOrDefault()