我有一個抽象類,其中包含許多固定對象,通常是各種類型的字典和列表。然後有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