考虑以下情况:
可以有类别
; Children
派生自 Categories
;在某个地方,必须有一个如下所示的方法:
ChildType[] Get(ParentType parent) { ... }
ChildType
不是从 ParentType
派生的;它们之所以如此命名,是因为该方法是一个工厂方法,用于根据父级的 ID 获取子级。
目前我有一些看起来像这样的东西:
static class CatFactory<ChildType, ParentType> : Category
where ParentType: Category
where ChildType: Category, new()
{
public static ChildType[] Get(string catname, ParentType parent)
{
// ...
}
}
class ParentCategoryA : Category { }
class ParentCategoryB: Category { }
class ChildCategoryA: Category { }
class ChildCategoryB: Category { }
然后我会这样调用工厂:
CatFactory<ChildCategoryA, ParentCategoryA>.Get(someparent);
这样做的目的是 - 给定一些具有 ID 的强类型父实例,使用该 ID 访问 Web 服务,然后反序列化一个新的子实例。
这在我嘴里留下了不好的味道。在我看来,ChildCategoryA
应该知道它的父级是ParentCategoryA
,并且应该能够调用ChildCategoryA.Get(someparent)
。这当然可以通过为子级的每个实现定义一个static Get()
来实现,但这需要大量的重复代码。
那么 - 最好的方法是什么?单独的工厂类,还是不?
最佳答案
我觉得这个问题有点令人困惑。这就是我认为你想要做的:
编写一个静态方法,给定一个 Category 对象,该方法知道如何查找指定类型的该类别的所有子项。
如果这是正确的,那么我会建议一种扩展方法:
static class CategoryExtensions
{
public static T[] GetChildren<T>(this Category parent)
where T : Category, new()
{
// Do whatever...
}
}
然后,给定任何类别对象,您可以编写:
ChildCategory[] children = parent.GetChildren<ChildCategory>();
关于多个派生类的泛型工厂的 C# 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14245327/