這是在使用 .net Framework v4.8 的 asp.net webforms 應用程式上
(我知道這是舊技術,我不應該用它編碼新專案。我已經十多年沒有在 asp.net 中寫過任何東西了,當我以這種方式編碼時,webforms 是要使用的東西。我會的學習 Blazor 并在未來在更現代的平臺上重新編碼。抱歉,我只是想阻止評論中的任何“你為什么使用網路表單”。)
我在頁面上有一個如下所示的引數:
public Dictionary<string, string> StrategySubtypes {
get
{
return (ViewState["StrategySubtypes"] == null) ? new Dictionary<string, string>() : (Dictionary<string, string>)ViewState["StrategySubtypes"];
}
set
{
ViewState["StrategySubtypes"] = value;
}
}
當我使用下面的代碼在字典上呼叫 add 方法時,代碼不會回傳錯誤,但它也不會將新的字典項寫入 ViewState。
protected void btnAddSubtype_Click(object sender, EventArgs e)
{
Dictionary<string, string> tmpStrategySubtypes = StrategySubtypes;
StrategySubtypes.Add(txtSubtype.Text, "new");
lbSubtypes.DataSource = StrategySubtypes;
lbSubtypes.DataTextField = "Key";
lbSubtypes.DataValueField = "Value";
lbSubtypes.DataBind();
txtSubtype.Text = String.Empty;
}
它只是進入了以太。我相信正在發生的事情是,當我呼叫 Add 方法時,我從 get 訪問器獲取字典,并且我正在對該字典執行 add 方法,但是 Add 沒有呼叫 set 訪問器,所以我只是針對相同的原始字典。
我正在使用以下代碼解決此問題
protected void btnAddSubtype_Click(object sender, EventArgs e)
{
Dictionary<string, string> tmpStrategySubtypes = StrategySubtypes;
tmpStrategySubtypes.Add(txtSubtype.Text, "new");
StrategySubtypes = tmpStrategySubtypes;
tmpStrategySubtypes.GetEnumerator().Dispose();
lbSubtypes.DataSource = StrategySubtypes;
lbSubtypes.DataTextField = "Key";
lbSubtypes.DataValueField = "Value";
lbSubtypes.DataBind();
txtSubtype.Text = String.Empty;
}
但這似乎不優雅,而且笨重。還有必須要達到這更好,更正確的做法。我的問題是,如果我使用一個物件作為公共引數,有沒有辦法直接在該引數上呼叫方法并讓它使用 set 訪問器存盤結果?
uj5u.com熱心網友回復:
在 get 訪問器中,如果為 null,當前代碼會創建一個新字典,但它永遠不會使用此新字典實體設定 ViewState。因此,當您再次詢問 StrategySubtypes 屬性的值時,null 仍然存在并回傳一個新字典。
輕松修復:
public Dictionary<string, string> StrategySubtypes {
get
{
var dict = ViewState["StrategySubtypes"] as Dictionary<string, string>;
if(dict == null)
{
dict = new Dictionary<string, string>();
ViewState["StrategySubtypes"] = dict;
}
return dict;
}
set
{
ViewState["StrategySubtypes"] = value;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/367781.html
上一篇:C#制作一個帶階段的貨幣系統
