在下面的例子中,我怎麼能得到SpecialThingDB返回一個SpecialThings列表,而不必像我做的那樣重新實現ThingDB的所有方法?在C#中,派生管理器類如何在不重新實現所有內容的情況下返回派生類的實例?
public class Thing
{
public readonly string Color;
public readonly int Weight;
public Thing(string color, int weight)
{
Color = color;
Weight = weight;
}
// Some methods
}
public class ThingDB
{
public List<Thing> GetByColor(string color)
{
var things = new List<Thing>();
// Get things from the database's Thing table
return things;
}
public List<Thing> GetByWeight(int weight)
{
var things = new List<Thing>();
// Get things from the database's Thing table
return things;
}
}
public class SpecialThing : Thing
{
public SpecialThing(string color, int weight) : base(color, weight)
{
}
// Some special methods
}
public class SpecialThingDB : ThingDB
{
// How do I have GetByColor and GetByWeight return SpecialThings here
// without completely re-implementing the base methods like below?
public List<SpecialThing> GetByColor(string color)
{
var specialThings = new List<SpecialThing>();
// Get things from the database's Thing table
return specialThings;
}
public List<SpecialThing> GetByWeight(int weight)
{
var specialThings = new List<SpecialThing>();
// Get things from the database's Thing table
return specialThings;
}
}
此外,有沒有更好的模式不必在我的數據庫中每個表兩班(一個代表一個記錄,另一個是一個管理器類)其他? (!感謝,the_joric)
UPDATE
給出的解決,這裏就是我改變了一下上面的代碼:
public class ThingDB<T> where T : Thing
{
public List<T> GetByColor(string color)
{
var things = new List<T>();
// Do some database stuff to fill things by color
return things;
}
public List<T> GetByWeight(int weight)
{
var things = new List<T>();
// Do some database stuff to fill things by weight
return things;
}
}
public class SpecialThing : Thing
{
public SpecialThing(string color, int weight)
: base(color, weight)
{
}
// Some special methods
}
public class SpecialThingDB : ThingDB<SpecialThing> { }
public class ThingDB : ThingDB<Thing> { } // For backward-compatibility
也許我不完全理解你,但不應該'base.GetByColor(color).Cast()'工作嗎? –
2012-02-21 16:09:54
可能,但我希望儘可能幹,並且不要在派生類中重新實現每個方法,即使這只是使用強制類型顯式調用基本方法。 – 2012-02-21 19:23:13