[英]Generics with inheritance design - need help to fix
我的設計有問題:
我有一些基礎課
public class ReportConfig<T> where T: class
{
public string ReportSavePath { get; set; }
public string ReportTitle { get; set; }
public T ReportData { get; set; }
}
並且可以將該類擴展為(提供的可能的子類之一):
public class CsvReportConfig<T> : ReportConfig<T> where T : class
{
// some extra class specific props
}
然后,我有一個ReportGenerator抽象類
public abstract class ReportGenerator<T> where T : ReportConfig<T>
{
public ReportGenerator(ReportConfig<T> config)
{
Config = config;
}
public ReportConfig<T> Config { get; set; }
public abstract ReportGenerationResult GenerateReport();
}
然后,我想將ReportGenerator
類擴展為:
public class Csv1ReportGenerator : ReportGenerator<CsvReportConfig<DataObj>>
{
public Csv1ReportGenerator (CsvReportConfig<DataObj> config) : base(config)
{
}
public override ReportGenerationResult GenerateReport()
{
throw new NotImplementedException();
}
}
在這里,我收到一個錯誤
CsvReportConfig<DataObj>
不能在通用類型或方法ReportGenerator<T>
用作類型參數'T'。
我在做什么錯,以及如何解決這個問題?
我相信這就是你想要做的
public class ReportGenerationResult { }
public class DataObj { }
public class ReportConfig<T> where T : class
{
public string ReportSavePath { get; set; }
public string ReportTitle { get; set; }
public T ReportData { get; set; }
}
public class CsvReportConfig<T> : ReportConfig<T> where T : class
{}
public abstract class ReportGenerator<T,U> where T : ReportConfig<U> where U : class
{
protected ReportGenerator(T config)
{
Config = config;
}
public T Config { get; set; }
public abstract ReportGenerationResult GenerateReport();
}
public class Csv1ReportGenerator : ReportGenerator<CsvReportConfig<DataObj>, DataObj>
{
public Csv1ReportGenerator(CsvReportConfig<DataObj> config) : base(config)
{
}
public override ReportGenerationResult GenerateReport()
{
throw new NotImplementedException();
}
}
這些是所做的主要更改。
ReportGenerator
這是主要更改。 在任何實現中,您似乎都想為屬性Config
指定通用類型參數( 僅限於類型為ReportConfig<T>
或擴展為ReportConfig<T>
)。 為此,並保持ReportConfig.ReportData
泛型,您必須使用2個泛型類型參數,其中第二個類型參數被重用以約束ReportConfig<T>
。 Csv1ReportGenerator
現在,當它繼承ReportGenerator<CsvReportConfig<DataObj>, DataObj>
而不是ReportGenerator<CsvReportConfig<DataObj>>
,現在使該類型具有屬性Config
,該屬性將被限制為類型CsvReportConfig<DataObj>
,這是您要嘗試的類型做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.