代码之家  ›  专栏  ›  技术社区  ›  aj.esler

创建一个变量,该变量可以存储泛型类型的不同实例,并对该变量调用给定的方法,而不管类型如何

  •  4
  • aj.esler  · 技术社区  · 15 年前

    我正在尝试创建通用模拟运行程序。每个模拟实现各种接口。最后,它将在运行时通过DLL获取模拟类型,因此我无法事先了解这些类型。

    我的当前代码:

    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控件连接到模拟变量,这样我就可以执行如下操作

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

    不管当前绑定到tspace和tcell的类型是什么,都可以让它工作。

    当前,我收到错误消息说“错误10找不到类型或命名空间名称“u”(是否缺少using指令或程序集引用?)对T来说也是一样。

    我试过创建一个封装SimulationRunner的控制器类,但是我仍然有同样的问题,因为在创建它时,我必须传递tspace和tcell的类型,所以问题只是转移到另一个类。

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

    2 回复  |  直到 15 年前
        1
  •  6
  •   Igor Zevaka    15 年前

    解决方案是将非泛型方法和属性引入非泛型接口,这样接口的调用方就不必知道类接受哪些类型参数:

    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();
      }
    }
    
        2
  •  3
  •   Ilia G    15 年前

    您需要对其运行泛型的方法吗?

    如果不是,则为您的 SimulationRunner 把它用于你的 simulation 变量

    否则-那么,你就需要知道你要运行的方法,对吗?