问题
This is an odd thing I've just run into.
I have a web application with a small DataTable stored in the ApplicationCache to reduce the amount of queries to a separate since the data is a lookup table that doesn't change often.
I access this DataTable twice within a given page. Once to bind the data to a drop down list in my Page_Load method:
dtDeptDivAct = GetAllDeptDivActCodes()
dtDeptDivAct.DefaultView.Sort = "LongDescription ASC"
ddlDeptDivAccount.DataSource = dtDeptDivAct.DefaultView
ddlDeptDivAccount.DataTextField = "LongDescription"
ddlDeptDivAccount.DataValueField = "Id"
ddlDeptDivAccount.DataBind()
...and once to retrieve additional data from the table when an index is selected in my ddlDeptDivAct_SelectedIndexChanged event:
Dim dtDeptDivAct As DeptDivActDataTable
If ddlDeptDivAccount.SelectedIndex > 0 Then
dtDeptDivAct = GetAllDeptDivActCodes()
dtDeptDivAct.DefaultView.RowFilter = "Id = " & ddlDeptDivAccount.SelectedValue
txtAddFundingDept.Text = DirectCast(dtDeptDivAct.DefaultView(0).Row, DeptDivActRow).Department.ToString.PadLeft(2, Char.Parse("0"))
txtAddFundingDiv.Text = DirectCast(dtDeptDivAct.DefaultView(0).Row, DeptDivActRow).Division.ToString.PadLeft(2, Char.Parse("0"))
txtAddFundingAct.Text = DirectCast(dtDeptDivAct.DefaultView(0).Row, DeptDivActRow).Activity.ToString.PadLeft(3, Char.Parse("0"))
Else
txtAddFundingDept.Text = ""
txtAddFundingDiv.Text = ""
txtAddFundingAct.Text = ""
End If
Note: The GetAllDeptDivActCodes() method is a simple method that returns the table from the ApplicationCache object.
The web page works fine. I can select my value and the proper values are insterted into the TextBox. However, when I go to a different page and come back to this page. My drop down list only has 1 value available for selection.
When I pulled up the debugger, I noticed that upon returning to the web page, when the GetAllDeptDivActCodes method returns the DataTable from the cache, the DefaultView RowFilter property was still applied to the DataTable, which was causing the problem.
I have fixed the issue for now by simply resetting the the DefaultView RowFilter once processing is done in the SelectedIndexChanged event, but why is the Application returning what appears to be a reference to the DataTable in the application cache when I was expecting a seperate copy (or value) of the object?
回答1:
This is by design. Whenever you store an object in the Application State or Session State you are returned the actual object (or as you put it a reference to the object) when you access it. By design .NET objects are almost always passed by reference unless you specify otherwise. Forexample when passing objects to Functions they are passed by reference.
来源:https://stackoverflow.com/questions/394492/why-is-my-applicationcache-passing-back-a-reference-instead-of-a-value