2013-05-02 54 views
1

我在我的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,而且我的面向對象技能顯然是想要的。我應該怎麼做?

回答

5

您應該在類的構造函數中構造您的類需要的對象。您應該添加一個默認的構造是這樣的:

public LitHoldModifications() 
{ 
    Added = new Hashtable(); 
    Deleted = new Hashtable(); 
} 

然後你就可以在你的添加刪除該任務()和delete()方法,因爲你可以在這些方法中,這些成員變量就已經是有效的假設。

我也建議改變你的添加/刪除方法返回void。如果你想訪問新增/刪除的哈希表,你可以直接引用該屬性。

var myLitInstance = new LitHoldModifications(); 
myLitInstance.Add("value1", "value2"); 
Hashtable tbl = myLitInstance.Added; 
+0

這個作品非常漂亮,非常感謝! – Melanie 2013-05-02 18:29:29