普通班级的普通父母 [英] Generic Parent For Generic Class
问题描述
为此,我使用一个虚构的示例.说,我有一个类似Widget的类:
I am using a fictional example for this. Say, I have a Widget class like:
abstract class Widget
{
Widget parent;
}
现在,我的其他类将从该Widget类派生,但是假设我想在定义派生类型时在该类中施加一些约束,以使只有特定的类型"的widget可以成为特定类型的父对象.小部件.
Now, my other classes would be derived from this Widget class, but suppose I want to put some constraint in the class while defining the derived types such that only a particular "type" of widget can be parent to a particular type of Widget.
例如,我从Widget类派生了另外两个小部件WidgetParent和WidgetChild.在定义子类时,我想将父类的类型定义为WidgetParent,这样我就不必在每次使用父类时都将其类型转换为父类.
For example, I have derived two more widgets from the Widget class, WidgetParent and WidgetChild. While defining the child class, I want to define the type of parent as WidgetParent, so that I dont have to type cast the parent every time I use it.
准确地说,我想做的是这样:
Precisely, what I would have liked to do is this:
// This does not works!
class Widget<PType>: where PType: Widget
{
PType parent;
}
class WidgetParent<Widget>
{
public void Slap();
}
class WidgetChild<WidgetParent>
{
}
这样,当我想访问WidgetChild的父级时,而不是这样使用它:
So that when I want to access the parent of WidgetChild, instead of using it this way:
WidgetParent wp = wc.parent as WidgetParent;
if(wp != null)
{
wp.Slap();
}
else throw FakeParentException();
我想以这种方式使用它(如果可以使用泛型的话):
I want to use it this way(if I could use generics):
wc.parent.Slap();
推荐答案
通过仍然具有非通用类Widget
并使Widget<T>
从其派生,您应该能够使用获得的代码:
You should be able to use the code you've got by still having the non-generic class Widget
and making Widget<T>
derive from it:
public abstract class Widget
{
}
public abstract class Widget<T> : Widget where T : Widget
{
}
然后,您需要根据经验算出什么属于泛型类,哪些属于非泛型类……这可能是一个棘手的平衡行为.期望来回来回去相当多!
You then need to work out what belongs in the generic class and what belongs in the non-generic... from experience, this can be a tricky balancing act. Expect to go back and forth a fair amount!
这篇关于普通班级的普通父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!