Does .Net support curried generics?

前端 未结 2 998
予麋鹿
予麋鹿 2021-02-12 19:15

Suppose we have a nested generic class:

public class A {
    public class B { }
}

Here, typeof(A.B<>)<

相关标签:
2条回答
  • 2021-02-12 19:37

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

    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
    

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

    EDIT: 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)

    0 讨论(0)
  • 2021-02-12 19:46

    Is this what you have in mind?

       class AB<T, U>
       {
          protected T t;
          U u;
       }
    
       class C<U> : AB<int, U>
       {
          public void Foo()
          {
             t = 5;
          }
       }
    
    0 讨论(0)
提交回复
热议问题