[英]Generic class type constraint with a generic class having another constraint
Let's say I have a generic class假设我有一个通用的 class
public class G<T> {
}
and I want to declare final class as我想将最终 class 声明为
public class F<T> where T : G<T> {
}
that seems to be possible, but what if I want to complicate the task and add a constraint to the class G like that这似乎是可能的,但是如果我想使任务复杂化并像这样向 class G 添加约束怎么办
public class A {
}
public class DA : A {
}
public class DB : A {
}
public class G<T> where T : A {
}
and finally I want to do this最后我想这样做
public class F<T> where T : G<T> {
}
that does not work, it says T has to be of type A which is understandable and it looks like I can rewrite it like this这不起作用,它说 T 必须是 A 类型,这是可以理解的,看起来我可以像这样重写它
public class F<T, U> where T : G<U> where U : A {
}
but in this case the usage has a redundant declaration但在这种情况下,用法有一个多余的声明
public class DF : F<G<DA>, DA> {
}
I have to repeat DA twice when using class F even though it is quite clear if I use G as a generic type the generic type of G is DA.在使用 class F 时,我必须重复 DA 两次,即使如果我使用 G 作为泛型类型,G 的泛型类型是 DA 也很清楚。 Is there a way to avoid this redundancy?
有没有办法避免这种冗余?
And finally I want to do this
最后我想这样做
public class F<T> where T: G<T> { }
But this doesn't seem to make much sense.但这似乎没有多大意义。 You want
F
to be parametrized by T
which must be G<X>
where X
is T
again, which is G<X>
, where X
is T
again and so on... This is a recursive definition.您希望
F
由T
参数化,它必须是G<X>
,其中X
再次是T
,即G<X>
,其中X
再次是T
等等......这是一个递归定义。
I think what you actually want to define is something like (all examples are invalid C#)我认为您真正想要定义的是(所有示例都是无效的 C#)
public class F<T1<T2>> where T1 : G<T2> where T2 : A {
}
or maybe或者可能
public class F<T1> where T1 : G<T2> where T2 : A {
}
or maybe或者可能
public class F<G<T>> where T : A {
}
Those kind of "generics of generics" are called higher-kinded types , but C#, unfortunately, does not support them.那些“泛型的泛型”被称为更高种类的类型,但不幸的是,C# 不支持它们。 Haskell does for instance and some other functional languages do too.
例如,Haskell 可以,其他一些函数式语言也可以。
There is a C# library that mimics HKTs and it uses the workaround you found: specifying the inner type twice.有一个模仿 HKT 的C# 库,它使用您找到的解决方法:指定内部类型两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.