我在我的ASP.Net項目中創建了一個名爲LitHoldModifications的類。這裏是代碼:需要C#類的方法,堅持信息已存在對象
[Serializable]
public class LitHoldModifications
{
private Boolean _changed;
private Hashtable _added;
private Hashtable _deleted;
public Boolean Changed
{
get { return _changed; }
set { _changed = value; }
}
public Hashtable Added
{
get { return _added; }
set { _added = value; }
}
public Hashtable Deleted
{
get { return _deleted; }
set { _deleted = value; }
}
public Hashtable Add(String item1, String item2)
{
Added = new Hashtable();
Added.Add(item1, item2);
return Added;
}
public Hashtable Delete(String item1, String item2)
{
Deleted = new Hashtable();
Deleted.Add(item1, item2);
return Deleted;
}
}
我遇到的問題是,我需要能夠添加多個項目到這個類的實例。我不得不這樣做的代碼是(在一個aspx頁面):
public LitHoldModifications AffectedEmployeeModifications
{
get
{
if (ViewState["AffectedEmployeeModifications"] != null)
return (LitHoldModifications)ViewState["AffectedEmployeeModifications"];
else
return null;
}
set
{
ViewState["AffectedEmployeeModifications"] = value;
}
}
protected void ProcessAffectedviaJavascript()
{
string[] employees = HiddenEmployeesPopup.Value.Split('|');
if (employees.Length>1) {
foreach (string s in employees)
{
if (s.Length > 1)
{
string Anumber = s.Split('@')[0];
string AName = s.Split('@')[1];
ListItem item = new ListItem();
item.Text = AName;
item.Value = Anumber;
lstSelEmployees.Items.Add(item);
//Clear values in temp hidden field:
HiddenEmployeesPopup.Value = "";
AffectedEmployeeModifications.Add(Anumber, AName);
AffectedEmployeeModifications.Changed = true;
}
}
}
當我運行我的代碼,並獲得ProcessAffectedviaJavascript(),字符串[]員工填充了多個名字,但每次碼獲取到AffectedEmployeeModifications.Add行....由Add方法創建並返回新的Hashtable,因此已添加到AffectedEmployeeModifications的員工的任何早期字符串都將丟失。我能想到的來解決這個問題的唯一方法是改變Add方法採取AffectedEmployeeModifications作爲參數,並做到這一點:
public Hashtable Add(Hashtable lhm, String item1, String item2)
{
lhm.Add(item1, item2);
return lhm;
}
,然後在我的aspx.cs:
AffectedEmployeeModifications = AffectedEmployeeModifications.Add(AffectedEmployeeModifications, Anumber, AName);
這雖然看起來不是OOP-y,而且我的面向對象技能顯然是想要的。我應該怎麼做?
這個作品非常漂亮,非常感謝! – Melanie 2013-05-02 18:29:29