. net支持curry泛型吗?
本文关键字:泛型 curry 支持 net | 更新日期: 2023-09-27 17:49:45
假设有一个嵌套的泛型类:
public class A<T> {
public class B<U> { }
}
这里,typeof(A<int>.B<>)
本质上是一个有两个参数的泛型类,其中只有第一个参数是有约束的。
如果我有一个有两个参数的类
public class AB<T, U> { }
是否有办法指"AB
与T=int
和U
保持开放"?如果没有,这是c#的限制,还是CLR的限制?
显然在c#中不能这样做,你必须指定两个类型参数,或者不指定。
CLR似乎也不支持,A<int>.B<>
和A<string>.B<>
引用同一类型:
Type t1 = typeof(A<int>).GetNestedType("B`1");
Type t2 = typeof(A<string>).GetNestedType("B`1");
// t1.Equals(t2) is true
两个类型的封闭类型都是A<>
(open泛型)
编辑:进一步的测试表明typeof(A<int>.B<string>)
实际上是一个密度2的泛型类型,不是一个密度1的嵌套泛型类型…typeof(A<int>.B<string>).GetGenericArguments()
返回一个包含typeof(int)
和 typeof(string)
的数组。因此,typeof(A<int>.B<>)
实际上相当于(A.B)<int, >
,这是不支持的(泛型类型不能部分关闭)
这是你想要的吗?
class AB<T, U>
{
protected T t;
U u;
}
class C<U> : AB<int, U>
{
public void Foo()
{
t = 5;
}
}
可以使用Func<int,int>泛型:将多个参数作为单个函数传递,返回一个类型。将多个参数作为单个形参传递。
[Fact]
public async Task TestCurried()
{
Func<int, Func<int, int>> curried = x => y => x + y;
int sum = curried(1)(3);
Assert.Equal(sum.ToString(), "4");
}
see
https://blog.tchatzigiannakis.com/generics-as-super-functions/