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

时间:2020-07-22 12:12:18

标签: c# generics inheritance abstract-class

我遇到的问题类似于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#中使用泛型,并建议将泛型类和静态类组合使用。 但是,我不希望整个类,而只希望一个参数是通用的。 有什么想法要实现吗?

1 个答案:

答案 0 :(得分:3)

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

<template>
<span>
    <label v-if="title">{{title}}</label>
    <v-select
        :options="options"
        :label="label"
        :placeholder="placeholderText"
        :close-on-select="closeOnSelectValue"
        :disabled="isDisabled"
        :multiple="multiple"
        :value="value"
        @input="handleInput($event)"
        :loading="isLoading"
        :reduce="reduceKey"
    ></v-select>
</span>
</template>

<script>
export default
{
  props: {
        returnKey: {
            type: String,
            default: null,
        },
  },
  methods:
  {
    reduceKey(option)
    {
      return option[this.returnKey] || option;
    }
  }
}

然后,在子类中:

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