2010-08-12 61 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可變

否則 - 那麼,你需要了解你要去想運行方法, 對?

相關問題