【发布时间】:2018-05-14 11:03:02
【问题描述】:
下面是 C++、C# 和其他类似语言的完美构造。为什么这在 Kotlin 中是不可能的
open class EndPoint<T> (url: String): T{
...
}
class BlueEndPoint: EndPoint<BlueInterface>{}
class RedEndPoint: EndPoint<RedInterface>{}
【问题讨论】:
下面是 C++、C# 和其他类似语言的完美构造。为什么这在 Kotlin 中是不可能的
open class EndPoint<T> (url: String): T{
...
}
class BlueEndPoint: EndPoint<BlueInterface>{}
class RedEndPoint: EndPoint<RedInterface>{}
【问题讨论】:
因为 Kotlin 使用泛型,而不是模板。它只有一个 EndPoint 类,而不是像 C++ 那样为每个 T 创建一个新类。
在 JVM 上,这个类需要恰好扩展一个超类(可能是 Object)和一组特定的接口(可能没有)。 IE。你不能让 EndPoint<BlueInterface> 实现 BlueInterface 而不是 RedInterface,反之亦然 EndPoint<RedInterface>。
根据 MSDN,它在 C# 中也不起作用(我相信 CLR 在定义类时也有相同的要求):
C# does not allow the type parameter to be used as the base class for the generic type.
这里的例外是 C++。
【讨论】:
: T 正是引用的行所不允许的,而 CRTP 在 C#、Java 和 Kotlin 中工作得很好。
它是由 JVM 泛型限制引起的。更多信息,您可以阅读 [这里] (https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html)。
【讨论】: