【发布时间】:2020-11-11 23:31:06
【问题描述】:
我有一个类似于this thread 的问题,但我的有点不同。
我想创造这样的东西
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# 中使用泛型,并建议将泛型类和静态类结合使用。 但是,我不希望整个类,而只希望一个参数是通用的。 有什么想法可以实现吗?
【问题讨论】:
-
为什么构造函数需要是泛型的?
data只是设置一个字段,那么有什么问题:protected Plot(IDataPoint[] data, GameObject plotModel, Vector2 plotCenter = default)? -
构造函数本身不能直接使用泛型。要么将抽象类设为泛型,要么在构造函数中使用
IDataPoint数组。 -
因为如果我尝试将
BarDataPoint[]传递给Plot构造函数,它会说它无法将BarDataPoint[]转换为IDataPoint[]。但我也不想将IDataPoint[]传递给BarPlot构造函数,因为这不是正确的类型 -
BarDataPoint是否实现了IDataPoint?如果是这样,那么应该没有问题。如果没有,泛型无论如何也无济于事。
标签: c# generics inheritance abstract-class