2012-07-30 42 views
0

我在設計使用命令模式但泛型的解決方案時遇到了一些麻煩。基本上,我定義了一個通用接口,它只有一個返回通用對象列表的方法。通用泛型列表

public interface IExecute<T> 
{ 
    List<T> Execute(); 
} 

public class SimpleExecute : IExecute<int> 
{ 
    public List<int> Execute() 
    { return a list of ints... } 
} 

public class Main 
{ 
    private List<IExecute<T>> ExecuteTasks; // This is not valid in C# 
} 

由於仿製藥的泛型列表是無效的,我實現了一個非通用接口IExceute並提出了通用接口擴展非泛型之一,是能夠創建一個列表

public interface IExecute {} 

public interface IExecute<T> : Execute 
{ 
    List<T> Execute(); 
} 

private List<IExecute> ExecuteTasks; 

但是,現在我不確定如何循環ExecuteTasks並調用execute方法。

我盡力解釋了這個問題。請讓我知道你是否需要我的問題的進一步解釋。

感謝

+3

如果'IExecute'的實例不是全部都是相同的類型,那麼泛型提供了什麼好處? – mellamokb 2012-07-30 21:31:53

+0

因此,每個'Execute()'返回'List '對於一些未知的'T'。你想對結果做什麼? – svick 2012-07-30 21:34:45

+0

我將使用反射和類型信息來確定對象類型並根據對象的屬性信息確定工作表的名稱,然後將它們寫回到Excel電子表格中。 – user320587 2012-07-30 21:42:33

回答

2

你能做的最好的是這樣的:

public interface IExecute { IList Execute(); } 

然後,例如:

public class SimpleExecute : IExecute<int> 
{ 
    public List<int> Execute() 
    { return a list of ints... } 
    IList IExecute.Execute() { return this.Execute(); } 
} 

(注意非明確的接口成員實現通用IExecute.Execute()

然後:

List<IExecute> iExecuteList = //whatever; 
foreach (var ix in iExecuteList) 
{ 
    IList list = ix.Execute(); 
} 

你不能在編譯時具體的泛型列表類型(例如,IList<string>IList<int>)出於同樣的原因,不能將一個int,並在同一個通用列表string(除非類型參數是object)。

0

嘗試使用foreach遍歷每個項目的循環:

foreach(var item in ExecuteTasks) 
{ 
    item.Execute(); 
    //... 
} 
1
public class Main 
{ 
    private List<IExecute<T> ExecuteTasks; // This is not valid in C# 
} 

有2個錯誤的位置:

  • T是一個未知的類。您應該指定了正確的類型

  • 列表<沒有右括號'>'。每個開放支架必須有一個閉合的支架。它應該看起來像List<IExecute<T>>

+0

我認爲這裏的要點是它應該是一個具有不同'T'的任務列表。 – svick 2012-07-30 21:37:34

+0

1.是的,這就是問題的要點...... 2.很明顯OP是一個錯字。 – mellamokb 2012-07-30 21:37:46

+0

我知道這不是他想聽到的答案,但他犯了一些錯誤,我試圖糾正它們。 – HeM01 2012-07-30 21:39:18

1
List<IExecute<T>> ExecuteTasks 

無效,因爲T在包含類中的任何地方都沒有定義。

像這樣的東西應該工作而不是雖然:

List<IExecute<Object>> ExecuteTasks; 

ExecuteTasks.Add(new SimpleExecute()); 

或者

public class Main<T> 
{ 
    List<IExecute<T>> ExecuteTasks 
} 
0

當您使用泛型,認爲IExecute<Class1>IExecute<Class2>一個完全不同的接口。在這種情況下,如果您要在兩者中調用通用方法,則需要另一個接口;例如IExecute

public interface IExecute<T> 
{ 
    List<T> Execute(); 
} 

public interface IExecute 
{ 
    IList Execute(); 
} 

public class SimpleExecute : IExecute<int>, IExecute 
{ 
    IList IExecute.Execute() 
    { 
     return Execute(); 
    } 

    public List<int> Execute() 
    { 
     return new List<int>(); 
    } 
} 

然後,循環,你可以簡單地使用foreach和/或LINQ。

List<IExecute> entries = new List<IExecute> {new SimpleExecute()}; 

foreach (var result in entries.Select(x => x.Execute())) 
{ 
} 

什麼你正在努力實現似乎是正確的,因爲你認爲IExecute作爲一個單一的接口,但實際上它是一個「模板」,這將在編譯時創建的接口。