【问题标题】:Use generic type in abstract class constructor在抽象类构造函数中使用泛型类型
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 很高兴为您提供帮助 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多