gpt4 book ai didi

c# - 在 C# 中,派生管理器类如何在不重新实现所有内容的情况下返回派生类的实例?

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:49 25 4
gpt4 key购买 nike

在下面的示例中,我如何才能让 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com