问题描述
昨天,我在向朋友们解释C#的通用约束.在演示where T : CLASSNAME
约束时,我鞭打了这样的内容:
Yesterday, I was explaining C#'s generic constraints to my friends. When demonstrating the where T : CLASSNAME
constraint, I whipped up something like this:
public class UnusableClass<T> where T : UnusableClass<T>
{
public static int method(T input){
return 0;
}
}
看到它可以编译真的很惊讶.然而,经过一番思考,从编译器的角度来看,我认为这是完全合法的-UnusableClass<T>
与该约束中可以使用的任何其他类一样多.
And was really surprised to see it compile. After a bit of thinking, however, I figured it was perfectly legal from the point of view of the compiler - UnusableClass<T>
is as much of a class as any other that can be used in this constraint.
但是,这留下了两个问题:如何使用此类?有可能
However, that leaves a couple of questions: how can this class ever be used? Is it possible to
- 实例化吗?
- 要继承吗?
- 调用其静态方法
int method
?
如果可以,怎么办?
如果这些中的任何一个是可能的,T
的类型是什么?
If any of these is possible, what would the type of T
be?
推荐答案
好吧.
public class Implementation : UnusableClass<Implementation>
{
}
完全有效,正因如此
var unusable = new UnusableClass<Implementation>();
和
UnusableClass<Implementation>.method(new Implementation());
有效.
因此,可以的,可以通过提供一个继承类型作为type参数来实例化,并且与对static方法的调用类似.例如,它对于树状结构很有用,您需要在该树状结构中通常指定节点具有的子代类型,而节点本身的类型相同.
So, yes, it can be instantiated by supplying an inheriting type as the type parameter, and similarly with the call to the static method. It's for instance useful for tree-like structures where you want to generically specify the type of children the node has, while it being the same type itself.
这篇关于指定类本身的通用类的基类约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!