是否支持.NET泛型咖喱? [英] Does .Net support curried generics?

查看:191
本文介绍了是否支持.NET泛型咖喱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个嵌套的泛型类:

Suppose we have a nested generic class:

public class A<T> {
    public class B<U> { }
}

下面,的typeof(A&LT; INT&GT; .B&LT;&GT;)。在本质上是一个通用类,其中只有第一个绑定两个参数

Here, typeof(A<int>.B<>) is in essence a generic class with two parameters where only the first is bound.

如果我有一个类有两个参数

If I have a single class with two parameters

public class AB<T, U> { }

有没有一种方法来指代 AB T = INT U的保持开放?如果没有,这是一个C#的限制,或CLR限制?

Is there a way to refer to "AB with T=int and U staying open"? If not, is this a C# limitation, or a CLR limitation?

推荐答案

显然它不能在C#中做,你必须指定任何两个类型参数,或无。

Apparently it can't be done in C#, you have to specify either both type parameters, or none.

和它似乎并不由CLR无论是支持, A&LT; INT&GT; .B&LT;&GT; A&LT;字符串&GT; .B&其中;&GT; 指的是同一类型:

And it doesn't seem to be supported by the CLR either, A<int>.B<> and A<string>.B<> refer to the same type:

Type t1 = typeof(A<int>).GetNestedType("B`1");
Type t2 = typeof(A<string>).GetNestedType("B`1");
// t1.Equals(t2) is true

这两种类型的封装类型为 A&LT;&GT; (开放式泛型类型)

The enclosing type of both types is A<> (open generic type)

编辑:进一步测试显示,的typeof(A&LT; INT&GT; .B&LT;字符串&GT;)实际上是一个泛型类型的元数2,元数1的嵌套泛型类型... 的typeof(A&LT; INT&GT; .B&LT;字符串&GT;)。GetGenericArguments()返回与 typeof运算(INT)的 typeof运算(字符串)。因此,的typeof(A&LT; INT&GT; .B&LT;&GT;)实际上相当于(AB)&LT; INT,&GT; ,系统不支持(通用类型不能被部分地关闭)

further testing shows that typeof(A<int>.B<string>) is actually a generic type of arity 2, not a nested generic type of arity 1... typeof(A<int>.B<string>).GetGenericArguments() returns an array with typeof(int) and typeof(string). So typeof(A<int>.B<>) would actually be equivalent to (A.B)<int, >, which isn't supported (a generic type can't be partially closed)

这篇关于是否支持.NET泛型咖喱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆