2017-09-27 57 views
2

我有我的設計問題:泛型與繼承設計 - 需要幫助解決

我有一些基類

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>不能被用作類型參數「T」在 通用類型或方法ReportGenerator<T>

我在做什麼錯誤以及如何糾正?

回答

4

我相信這是你正在嘗試做的

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.ReportData泛型,你必須使用2個泛型類型參數,其中第二個類型參數被重用來約束ReportConfig<T>
  • Csv1ReportGenerator - 現在,當這個繼承ReportGenerator<CsvReportConfig<DataObj>, DataObj>而不是ReportGenerator<CsvReportConfig<DataObj>>現在讓這種類型的擁有財產性Config這將是制約鍵入CsvReportConfig<DataObj>這就是你要怎樣做。
+2

是的,正是我想通了 - 這是正確的答案。謝謝 – pitersmx

+1

你能解釋一下,OP的代碼有什麼問題,以及爲什麼你的解決方案真正解決了它? –

+0

我錯過了一些泛型約束條件 – pitersmx