【发布时间】:2018-04-26 21:07:23
【问题描述】:
假设我有一个抽象基类,我想在其中声明与派生自该基类的类的类型匹配的成员。
public abstract class BaseClass
{
protected BaseClass parent;
}
public class DerivedClass1 : BaseClass
{
// parent could be of type DerivedClass2
}
public class DerivedClass2 : BaseClass
{
// parent could be of type DerivedClass1
}
这不起作用,因为每个派生类中的parent 字段可以是从BaseClass 派生的任何内容。我想确保DerivedClass1 中的parent 字段只能是DerivedClass1 类型。所以我在想也许我应该使用泛型。
public abstract class BaseClass<T> where T : BaseClass<T>
{
protected T parent;
}
这可能看起来令人困惑和循环,但它确实可以编译。它基本上是说parent 是T 类型,它必须派生自通用BaseClass。所以现在派生类可以如下所示:
public class DerivedClass : BaseClass<DerivedClass>
{
// parent is of type DerivedClass
}
问题是当我声明DerivedClass 时,我必须自己强制执行类型匹配。没有什么能阻止某人做这样的事情:
public class DerivedClass1 : BaseClass<DerivedClass2>
{
// parent is of type DerivedClass2
}
C# 是否有办法做到这一点,以便在基中声明的成员的类型肯定与派生类型匹配?
我认为这类似于这个 C++ 问题试图提出的问题:Abstract base class for derived classes with functions that have a return type of the derived class
【问题讨论】:
-
这称为 CRTP。
-
如果您希望父属性具有特定类型,那么为什么您需要担心该类型从哪个基类继承?您也不需要在抽象类中声明此属性。您只需要在适当的类中创建属性。
-
恐怕你的问题不清楚。我的意思是,很清楚你想要什么。但是,您现在应该已经发现 C# 没有提供这种约束。更重要的是,您的问题提供了关于 why 您认为此约束有用的零细节。如果类型参数
T实际上与声明类型不同,为什么这对您很重要?这将如何影响基类或派生类的实现?在这样的限制下,你不能做什么?请提供有关您的期望的更多详细信息。 -
您的问题的答案是“否”。
-
我担心包含更多关于我正在尝试创建的程序的细节会使我已经很长的问题的长度增加一倍。
标签: c# generics inheritance types abstract-base-class