为此,我使用了一个虚构的例子。比如说,我有一个Widget类,如下所示:
abstract class Widget
{
Widget parent;
}现在,我的其他类将从这个Widget类派生,但是假设我想在定义派生类型时在类中添加一些约束,以便只有特定“类型”的Widget才能成为特定类型的widget的父类。
例如,我从Widget类派生了另外两个小部件: WidgetParent和WidgetChild。在定义子类时,我希望将父类的类型定义为WidgetParent,这样就不必在每次使用时都对父类进行类型转换。
准确地说,我想要做的是:
// This does not works!
class Widget<PType>: where PType: Widget
{
PType parent;
}
class WidgetParent<Widget>
{
public void Slap();
}
class WidgetChild<WidgetParent>
{
}因此,当我想要访问WidgetChild的父级时,而不是这样使用它:
WidgetParent wp = wc.parent as WidgetParent;
if(wp != null)
{
wp.Slap();
}
else throw FakeParentException();我想这样使用它(如果我可以使用泛型):
wc.parent.Slap();发布于 2008-11-04 07:23:29
通过保留非泛型类Widget并使Widget<T>派生自该类,您应该能够使用已有的代码:
public abstract class Widget
{
}
public abstract class Widget<T> : Widget where T : Widget
{
}然后,您需要找出哪些属于泛型类,哪些属于非泛型...根据经验,这可能是一个微妙的平衡行为。预计来回来回的次数会很多!
发布于 2008-11-04 08:20:02
使用接口:
interface IContainerWidget { }
class Widget
{
private IContainerWidget Container;
}
class ContainerWidget : Widget, IContainerWidget
{
}发布于 2008-11-04 06:54:55
我不认为有一种语言机制可以让你这样做。
但是,您可能希望使用 将类的构造与类本身的分开。
比如说,创建一个WidgetFactory类
class WidgetFactory
{
Widget CreateWidget()
{
return new Widget();
}
}对于孩子们的班级,你也会让他们的工厂。比方说,一个WidgetParentFactory或WidgetChildFactory,或者你可以做一个通用工厂:
class WidgetFactory<T> where T : Widget
{
T CreateWidget()
{
return new T();
}
}然后,通过CreateWidget()方法,您可以控制类的实例化,这样就不会创建无效子类型。
class WidgetFactory<T> where T : Widget
{
T CreateWidget()
{
if (/*check the type T inheritance here*/)
return new T();
else
throw new Exception("Invalid inheritance");
}
}这对你来说应该是有用的。
附注:你能详细解释一下你为什么要这样做吗?
https://stackoverflow.com/questions/261086
复制相似问题