c# - 在抽象类构造函数中使用泛型类型
问题描述
我有一个类似于这个线程的问题,但我的有点不同。
我想创造这样的东西
public abstract class Plot
{
protected GameObject plotModel;
protected IDataPoint[] data;
protected GameObject[] plotModelInstances;
protected Plot<TDataPoint>(TDataPoint[] data, GameObject plotModel, Vector2 plotCenter = default) where TDataPoint : IDataPoint
{
this.data = data;
this.plotModel = plotModel;
plotModelInstances = new GameObject[data.Length];
this.plotCenter = plotCenter;
}
}
一个基类,它接受实现接口 IDataPoint 的泛型类型的数据数组。现在应该使用实现此接口的结构的数据数组来构造子类
public BarPlot(BarDataPoint[] data, GameObject plotModel, float barWidth = 1, float barHeight = 1, Vector2 = default) : base(data, plotModel, plotCenter)
{
this.barWidth = barWidth;
this.barHeight = barHeight;
}
上面链接的线程中的一个答案说构造函数不能在 C# 中使用泛型,并建议将泛型类和静态类结合起来。但是,我不希望整个类,而只希望一个参数是通用的。任何想法如何实现这一目标?
解决方案
您最好的选择可能是这样的:
public abstract class Plot<TDataPoint> where TDataPoint : IDataPoint
{
protected GameObject plotModel;
protected TDataPoint[] data; // Note: Changed IDatePoint[] to TDataPoint[]!
protected GameObject[] plotModelInstances;
// Note: Changed IDatePoint[] to TDataPoint[]!
protected Plot(TDataPoint[] data, GameObject plotModel, Vector2 plotCenter = default)
{
this.data = data;
this.plotModel = plotModel;
plotModelInstances = new GameObject[data.Length];
this.plotCenter = plotCenter;
}
}
然后,在子类中:
public class BarPlot : Plot<BarDataPoint>
{
public BarPlot(BarDataPoint[] data, GameObject plotModel, float barWidth = 1, float barHeight = 1, Vector2 = default)
: base(data, plotModel, plotCenter)
{
this.barWidth = barWidth;
this.barHeight = barHeight;
}
}
推荐阅读
- visual-studio - .NET SDK 3.0.100 不会出现在 Visual Studio 的下拉选项中
- sql - SQL - 如何通过 ID 获取 GrandParent、Parent、Child 的 Treeview
- c# - 将数据库列映射到自定义对象
- javascript - 当我调用它时,如何“自动化”我的程序来运行每个对象
- python - 将日期从 float64 转换为年月格式
- asp.net-mvc - MVC 将问题和答案视为一种形式,而 Post 操作不会为空
- javascript - 无法测试我的反应程序,纱线启动和测试不起作用
- css - 边框速记CSS内的边框半径
- python - 在 Pandas 中将原始日期转换为年/月/星期几
- android - Flutter 如何在无状态小部件中使用生命周期事件?应用关闭