首页 > 解决方案 > 在抽象类构造函数中使用泛型类型

问题描述

我有一个类似于这个线程的问题,但我的有点不同。

我想创造这样的东西

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# 中使用泛型,并建议将泛型类和静态类结合起来。但是,我不希望整个类,而只希望一个参数是通用的。任何想法如何实现这一目标?

标签: c#genericsinheritanceabstract-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;
    }
}

然后,在子类中:

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

推荐阅读