2013-08-07 62 views
3

我有一個綁定源可以綁定到A列表或B列表。取決於如果它是A或B,當我單擊「保存」時,我想調用保存適當的存儲庫的方法。函數返回不同的可能子類的列表

我能創造這個方法來檢查是否有列表是髒並需要保存:

private static bool IsDirty<T>(TList<T> list) where T : IEntity, new() 
{ 
    foreach (var entity in list) 
    { 
     if (entity.IsDirty) 
      return true; 
    } 
    return false; 
} 

不過,我有一個問題如下:

var list = CurrentTList<A>(); 

private TList<T> CurrentTList<T>() where T: IEntity, new() 
{ 
    switch (currentRatesTable) 
    { 
     case RatesTables.A: 
      return (TList<T>) _bindingSourceMaster.List; 
     case RatesTables.B: 
      return (TList<T>) _bindingSourceMaster.List; 
     default: 
      return null; 
    } 
} 

這是從數據源獲取當前列表的最佳方式嗎?我想避免使用開關,像這樣的,因爲它看起來不正確對我說:

switch (currentRatesTable) 
{ 
    case Form1.RatesTables.A: 
     var list = CurrentTList<A>(); 
    case Form1.RatesTables.B: 
     var list = CurrentTList<B>(); 
    // ... 
} 
+2

這聽起來像你真正需要的是一個接口 – Sayse

+0

你打算如何處理返回的'list'?什麼是TList? –

+0

一個TLIST是一個列表 - >公共類從TList :ListBase 其中T:IEntity,新的()和ListBase是 公共抽象類ListBase :的BindingList ,IBindingListView,IBindingList的,IList的,ICloneable,ICloneableEx,IListSource,ITypedList, IDisposable,IComponent,IRaiseItemChangedEvents,IDeserializationCallback – SerenityNow

回答

2

是啊,作爲Sayse說,你需要自己的接口和/或一個抽象類。如果有很多共享代碼,您可以從後者開始。這是來自舊測試項目的東西。它需要一種不同的方法(集合中的每個項目都與'髒'有關,並且有刪除方法可以搜索那些集合),但是您應該能夠根據需要進行調整:

[DataContract] 
public abstract class Dirty : Object 
{ 
    protected bool _isdirty; 
    public bool IsDirty 
    { 
     get { return _isdirty; } 
     set 
     { 
      _isdirty = value; 
     } 

} 

public abstract class DataStore<T> where T : Dirty 
{ 
    private string _path; 
    private string _tempFile; 

    protected DataStore(string path, string tempfile) 
    { 

     _path = path; 
     _tempFile = tempfile; 
    } 
} 

因此DataStore擁有操縱這些列表的邏輯。對我來說,這兩個類都是從Dirty繼承的類被序列化爲JSON,所以只要它們的成員具有正確的屬性,它們都得到了正確的序列化,因此每個類的存儲都沒有自定義邏輯。因此,所有他們需要做的,以創建自己的數據存儲是:

[DataContract] 
    public class Account : Abstracts.Dirty 
    { 
     #region DataStore fields and singleton 
     private static volatile StoreClass _store = new StoreClass(); 
     protected static StoreClass Store 
     { 
      get 
      { 
       return _store; 
      } 
     } 
     /// <summary> 
     /// Store is the data store for the Account class. This holds the active list of Accounts in a singleton, and manages the push/pull to the JSON file storage. 
     /// </summary> 
     protected class StoreClass : Abstracts.DataStore<Account> 
     { 
      #region Singleton initialization and Constructor 

      public StoreClass() 
       : base("accounts.json", "TEMP_accounts.json") 
      { 

      } 
      #endregion 
     } 
    } 

我切出在這個項目上只從數據存儲幾千行,但它是很瘋狂。其基本思想是在DataStore類中構建所需的邏輯以保存列表,並通過從StoreClass子級調用其構造函數的方式來保存/加載它。

+1

只是爲了解釋,因爲我不確定它與您的問題的關係有多清晰,請使用DataStore的概念來按住邏輯來拉右表,並且可以讓每個列表類都將其作爲一個字段,並調用其構造函數來定位其起始點。基本上你想讓他們都是他們自己的班級,所以你可以正確地給他們打電話,而不必做那種令你煩惱的事情。使應用程序將每個對象理解爲自己的對象,並將它們可能嚴重共享的邏輯放在一起,以便在DataStore下進行保存/加載。 –