我在從InProc會話狀態檢索一個會話變量的多個實例時遇到問題。檢索同一個asp.net會話變量的多個實例的問題
在以下代碼中,我將一個簡單的BusinessObject持久化到Page_Load事件的會話變量中。在點擊一個按鈕時,我嘗試將對象恢復回到同一個BusinessObject的兩個新聲明實例中。
所有的作品都很棒,直到我在第一個實例中更改其中一個屬性,它也會更改第二個實例。
這是正常的行爲嗎?我會認爲這些是新的實例,他們不會展示靜態行爲?
任何想法我錯了嗎?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
' create a new instance of a business object and set a containg variable
Dim BO As New BusinessObject
BO.SomeVariable = "test"
' persist to inproc session
Session("BO") = BO
End If
End Sub
Protected Sub btnRetrieveSessionVariable_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnRetrieveSessionVariable.Click
' retrieve the session variable to a new instance of BusinessObject
Dim BO1 As New BusinessObject
If Not Session("BO") Is Nothing Then BO1 = Session("BO")
' retrieve the session variable to a new instance of BusinessObject
Dim BO2 As New BusinessObject
If Not Session("BO") Is Nothing Then BO2 = Session("BO")
' change the property value on the first instance
BO1.SomeVariable = "test2"
' why has this changed on both instances?
Dim strBO1Property As String = BO1.SomeVariable
Dim strBO2Property As String = BO2.SomeVariable
End Sub
' simple BusinessObject class
Public Class BusinessObject
Private _SomeVariable As String
Public Property SomeVariable() As String
Get
Return _SomeVariable
End Get
Set(ByVal value As String)
_SomeVariable = value
End Set
End Property
End Class
我懷疑這可能是這種情況,但發現很難證明。由於我的Business Objects非常深入,需要深度複製,因此我避免了IClonable,並在課程中創建了自己的Copy方法,正如Brad Adams所建議的,http://blogs.msdn.com/brada/archive/2003/04 /09/49935.aspx – sw1sh