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

标签 c# generics

我正在尝试创建一个通用的模拟运行者。每个模拟实现各种接口(interface)。最终,它将在运行时通过 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();
}

无论当前绑定(bind)到 TSpace 和 TCell 的类型如何,它都可以正常工作。

目前我收到错误提示“错误 10 找不到类型或 namespace 名称‘U’(您是否缺少 using 指令或程序集引用?)”,对于 T 也是如此。

我已经尝试创建一个包装 SimulationRunner 的 Controller 类,但我仍然有同样的问题,因为我在创建它时必须传入 TSpace 和 TCell 的类型,所以问题就转移到了另一个类.

如何在变量中存储任何类型的模拟? 如何绑定(bind)控件以在任何类型的模拟中工作?

最佳答案

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

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();
  }
}

关于c# - 创建一个可以存储泛型类型的不同实例的变量,并在该变量上调用给定的方法,而不管类型如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3464605/

相关文章:

c# - POCO、ORM 和不变性。如何让它们协同工作?

c# - 使用 DataContractJsonSerializer 将字典序列化为 JSON 对象

java - corda实现通用vault查询

java - Wicket 通用组件设计模式

c# - 当项目在枚举时发生变化会影响枚举吗?

c# - CosmosDb SDK v3 是否在批量插入时自动重试?

javascript - MVC 导航栏主页按钮获取请求出现问题

c# - 如何在没有循环的情况下用 100 个空 List<T> 填充 list<list<T>>?

scala - Scala 中的 A[B[C]] 类型,即嵌套类型构造函数

java - 使用两个不同的泛型参数调用泛型函数仍然可以编译