我刚刚开始使用泛型,并对如何实现以下方案感到困惑。
这是我的基类:
--no-ff
在我的实现中,我想将具体列表传递给覆盖。类似的东西:
public abstract class UnclaimedProperty
{
public abstract string Key { get; }
public virtual void Process() { }
public virtual void Process(string FileName) { }
abstract public void WriteReport<T>(List<T> PropertyRecords, string FileName);
}
}
我收到错误:
public class PennUnclaimed : UnclaimedProperty
{
public override void Process(string FileName)
{
var reportDollarRecords = new List<PennUnclaimed>();
//add items here
WriteReport(reportDollarRecords, "PennCash");
}
public override void WriteReport(List<UnclaimedProperty> PropertyRecords, string FileName)
{
//write report here
}
实现这个的正确方法是什么?
答案 0 :(得分:2)
根据您的评论,考虑将抽象类设为通用。
public abstract class UnclaimedProperty<T> where T : UnclaimedProperty<T> {
public abstract string Key { get; }
public virtual void Process() { }
public virtual void Process(string FileName) { }
abstract public void WriteReport(List<T> PropertyRecords, string FileName);
}
这样的实现看起来像这样
public class PennUnclaimed : UnclaimedProperty<PennUnclaimed> {
public override void Process(string FileName) {
var reportDollarRecords = new List<PennUnclaimed>();
//add items here
WriteReport(reportDollarRecords, "PennCash");
}
public override void WriteReport(List<PennUnclaimed> PropertyRecords, string FileName) {
//write report here
}
public override string Key {
get {
return string.Empty; //TODO:return key
}
}
}
泛型参数的抽象类约束将允许它成为当前正在实现的类的类型。