我在设计一个使用命令模式但使用泛型的解决方案时遇到了一些问题。基本上,我定义了一个泛型接口,它只有一个返回泛型对象列表的方法。
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方法。
我已经尽力解释这个问题了。如果你需要进一步解释我的问题,请让我知道。
谢谢
发布于 2012-07-31 05:42:41
你最多只能这样做:
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)。
发布于 2012-07-31 05:36:39
public class Main
{
private List<IExecute<T> ExecuteTasks; // This is not valid in C#
}这里有两个错误:
List<IExecute<T>>发布于 2012-07-31 05:47:41
List<IExecute<T>> ExecuteTasks 无效,因为T未在包含类中的任何位置定义。
不过,这样的代码应该是有效的:
List<IExecute<Object>> ExecuteTasks;
ExecuteTasks.Add(new SimpleExecute());或
public class Main<T>
{
List<IExecute<T>> ExecuteTasks
}https://stackoverflow.com/questions/11729891
复制相似问题