我有一个抽象类,其中包含许多固定对象,通常是各种类型的字典和列表。然后有ReadData和WriteData的抽象方法。然后,我有两种不同的抽象类实现,一种是根据“文本记录”标准写入数据,另一种是根据定义的XML模式写入其他XML。使用泛型转换方法在抽象类的不同实现之间转换
因此,除了不同的读写方式外,这两种实现方式是相同的。
我现在想要做的是在数据读取格式1中,然后把它写成格式2.我可以通过编写方法,如.ToFormat2()
和在各自所属类别.ToFormat1()
,大概.FromFormat2()
和做到这一点很容易.FromFormat1()
如果我想要完整性。但是这些例程本质上是一样的,而当我需要格式3并且不希望在每一个中快乐地实现两个或多个相同的“到”方法时,我正在考虑未来(不太遥远)的未来。类。这是浪费时间,很难调试/改变,只是不好。
所以我一直在试图在抽象类中编写一个通用转换器。下面的代码说明了我到目前为止所做的原理:
public abstract class Test
{
public string Type;
public Dictionary<string, string> Dic1;
public Dictionary<string, int> Dic2;
public abstract void Read(string fileName);
public abstract void Write(string fileName);
public T ConvertTo<T>() where T : Test
{
T x = new T();
if (x.Type.Equals(this.Type)) { return this; }
x.Dic1 = this.Dic1;
x.Dic2 = this.Dic2;
return x;
}
}
public class Format1 : Test
{
// Constructor
public Format1() { Type = "Format1"; Dic1 = new Dictionary<string, string>(); Dic2 = new Dictionary<string, int>(); }
// Concrete implementations of abstract Read and Write for "Format1"
public override void Read(string fileName) { /* do reading stuff */ }
public override void Write(string fileName) { /* do writing stuff */ }
}
public class Format2 : Test
{
// Constructor
public Format2() { Type = "Format2"; Dic1 = new Dictionary<string, string>(); Dic2 = new Dictionary<string, int>(); }
// Concrete implementations of abstract Read and Write for "Format2"
public override void Read(string fileName) { /* do reading stuff */ }
public override void Write(string fileName) { /* do writing stuff */ }
}
但是编译器不喜欢这样。我在声明x
为新T
时出错,因为它没有new()约束,并且我不能返回this
,因为我无法隐式地将Test.Test
转换为T
。
我在做什么错?
我会考虑在你的对象中创建一个包装而不是使用继承来实现这一点。考虑到班级不应该真正关心如何加载/保存(单一责任原则)。如果您创建了具有Save()和Load()方法的ITestPersistance,则可以在此处包含所有逻辑而不会滥用继承。这意味着您可以在不更改任何其他代码的情况下添加ITestPersistance的新实现(即Format3TestPersistance)......如果您想要更灵活,可以将其扩展为ITestFormat和ITestPersistance ... – Milney
@Milney。嗯,是的。现在你已经指出了这一点。在那里遗传有点失落! – StuartR143