在C#中,派生的管理器类如何在不重新实现所有内容的情况下返回派生类的实例
本文关键字:派生 实现 实例 返回 情况下 管理器 新实现 | 更新日期: 2023-09-27 18:25:31
在下面的例子中,我如何让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;
}
}
此外,除了为数据库中的每个表提供两个类(一个代表一个记录,另一个是管理器类)之外,还有更好的模式吗?
更新
给定解决方案(谢谢,_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;
}
}
泛型:
[乔里奇在这场比赛中击败了我]
还有:可能,是的。使用对象关系映射器为您执行以下操作:http://en.wikipedia.org/wiki/Object-relational_mapping