在抽象 class 构造函数中使用泛型

Use generic type in abstract class constructor

我遇到的问题与 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;
    }
}

一个基数 class,它接受一个实现接口 IDataPoint 的泛型类型的数据数组。 子 class 现在应该用实现此接口的结构的数据数组构造

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# 中使用泛型,并建议结合使用泛型 class 和静态 class。 但是,我不希望整个 class 而是只有一个参数是通用的。 有什么想法可以实现吗?

您最好的选择可能是这样的:

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

然后,在 child class:

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