2010-08-12 60 views
4

我正在尝试创建一个通用模拟运行器。每个模拟实现了各种接口。最终,它会在运行时通过DLL获取模拟类型,所以我无法事先知道类型。创建一个变量,可以存储泛型类型的不同实例并调用变量的给定方法,而不管类型如何

我Currrent代码:

public class SimulationRunner<TSpace, TCell> 
    where TSpace : I2DState<TCell> 
    where TCell : Cell 
{ 
    public TSpace InitialState { get; set; } 
    public IStepAlgorithm<TSpace,TCell> StepAlgorithm { get; set; } 
    public IDisplayStateAlgorithm<TSpace,TCell> DisplayStateAlgorithm { get; set; } 
    public int MaxStepCount { get; set; } 
    ... 
    public void Run() {...} 
    public void Step() {...} 
    public void Stop() {...} 
} 

我想我的UI类来存储模拟亚军的泛型实例(如

public partial class UI : Window 
    { 
     SimulationRunner<TSpace,TCell> simulation; 
     ... 
    } 

,这样我可以分配不同类型的模拟,它的。 例如

simulation = new SimulationRunner<2DSpace, SimpleCell>(); 
// do stuff 
// start new simulation of different type 
simulation = new SimulationRunner<3DSpace, ComplexCell>(); 

我想让我的UI控件有线t Ø模拟变量,所以我可以做的事情一样

private void mnuiSimulate_Click(object sender, RoutedEventArgs e) 
{ 
    if (simulation != null) simulation.RunSimulation(); 
} 

,并有不管目前是什么类型的必然TSpace和T细胞发挥作用。

目前,我得到错误说一次“错误10类型或命名空间名称‘U’找不到(是否缺少using指令或程序集引用?)”,与同为T.

我已经尝试创建一个封装了SimulationRunner的控制器类,但是我仍然遇到同样的问题,因为当我创建它时,必须传入TSpace和TCell的类型,所以问题只是被移动到另一个类中。

如何在变量中存储任何类型的模拟? 如何将控件绑定到任何类型的模拟上?

回答

6

解决的办法是采取非通用的方法和属性成非通用接口,从而使界面的调用者不必知道类接受哪种类型的参数:

public interface ISimulationRunner { 
    public int MaxStepCount { get; set; } 
    ... 
    public void Run() {...} 
    public void Step() {...} 
    public void Stop() {...} 
} 

public class SimulationRunner<TSpace, TCell> : ISimulationRunner 
    where TSpace : I2DState<TCell> 
    where TCell : Cell 
{ 
    public TSpace InitialState { get; set; } 
    public IStepAlgorithm<TSpace,TCell> StepAlgorithm { get; set; } 
    public IDisplayStateAlgorithm<TSpace,TCell> DisplayStateAlgorithm { get; set; } 
} 

public partial class UI : Window 
{ 
    ISimulationRunner simulation = new SimulationRunner<2DSpace, SimpleCell>(); 
    private void mnuiSimulate_Click(object sender, RoutedEventArgs e) 
    { 
    if (simulation != null) simulation.RunSimulation(); 
    } 
} 
3

是您需要运行通用的方法吗?

如果没有,那么无论是定义一个非通用接口或基类的SimulationRunner和使用,为您的simulation可变

否则 - 那么,你需要了解你要去想运行方法, 对?

相关问题