我在我的 ASP.Net 项目中创建了一个名为 LitHoldModifications 的类。这是代码:
[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 方法返回,因此已添加到 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,而且我的 OOP 技能显然还不够。我该怎么做?