在下面的示例中,如何让 SpecialThingDB 返回 SpecialThings 列表,而不必像我一样重新实现 ThingDB 的所有方法?
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!),以下是我对上述代码所做的更改:
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
最佳答案
您可以使用泛型。就像下面这样:
public class ThingDB<T> where T: Thing
{
public List<T> GetByColor(string color)
{
var things = new List<T>();
// Get things from the database's Thing table
return things;
}
public List<T> GetByWeight(int weight)
{
var things = new List<T>();
// Get things from the database's Thing table
return things;
}
}
关于c# - 在 C# 中,派生管理器类如何返回派生类的实例而不重新实现所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9380799/