2011-12-17 36 views
1

我的泛型類遇到問題,並在運行時根據位於數據庫中的數據創建它們。在下面我試圖給出一個簡單的例子,用一個通用計數器類來跟蹤一列中值的出現頻率。處理基於數據庫數據在運行時實例化的泛型類

Counter是通用類,類Table模擬了兩列的數據庫表和Wrapper類包含的問題:)

基本上包裝類提供了DBMS獨立的接口來我的數據庫和揭露功能主義者的應用程序。請注意,我知道我的列有哪些數據類型,但如何爲我的計數器對象提供通用訪問權限?

public class Counter<T> 
{ 
    private Dictionary<T, int> _counter = new Dictionary<T,int>(); 

    public Counter() {} 

    public Counter(List<T> values) : this() 
    { 
     foreach (var item in values) 
      this.Add(item); 
    } 

    public void Add(T key) 
    { 
     if (!this._counter.ContainsKey(key)) 
      this._counter[key] = 0; 
     this._counter[key] += 1; 
    } 

    public int GetCount(T key) 
    { 
     return this._counter[key]; 
    } 
} 

public class Table 
{ 
    public List<int> IDs { get; private set; } 
    public List<String> Names { get; private set; } 

    public Table() 
    { 
     this.IDs = new List<int> { 1, 2, 3, 4, 5 }; 
     this.Names = new List<string> { "a", "b", "a", "c", "d" }; 
    } 
} 

public class Wrapper 
{ 
    private Table _table = new Table(); 

    public ... GetCounter(string columnName) 
    { 
     if (columnName == "id") 
      return new Counter<..>(this._table.IDs); 
     else if (columnName == "name") 
      return new Counter<..>(this._table.Names); 
    } 
} 

回答

1

您可以在GetCounter方法更改爲通用函數:

public Counter<T> GetCounter<T>(string columnName) 
{ 
    if (columnName == "id") 
     return new Counter<T>(this._table.IDs); 
    else if (columnName == "name") 
     return new Counter<T>(this._table.Names); 
} 
+0

謝謝...從初步的測試,我認爲這會工作:) – aweis 2011-12-17 19:06:18