编程语言
首页 > 编程语言> > 使用嵌套在通用类中的类作为C#中的类型参数

使用嵌套在通用类中的类作为C#中的类型参数

作者:互联网

具有以下定义:

public class Generic<T>
{
    public class Nested { }
}

鉴于ECMA参考§25.1指出:

Any class nested inside a generic class declaration or a generic
struct declaration (§25.2) is itself a generic class declaration,
since type parameters for the containing type shall be supplied to
create a constructed type.

我知道Nested需要type参数才能实例化.

我可以使用typeof获得泛型Type:

var type = typeof(Generic<>.Nested); 
// type.FullName: Namespace.Generic`1+Nested

有什么方法可以将其用作通用方法的类型参数,如下所示?

var tmp = Enumerable.Empty<Generic<>.Nested>(); 
// Error: Unexpected use of an unbound generic

如前所述,根据ECMA规范,我了解到实例化之前必须满足所有类型参数,但此处未创建任何对象.此外,Nested类不以任何方式使用类型参数:我只是想将其嵌套定义用于代码组织.

解决方法:

不,你不能那样做.如你所说

all the type parameters must be satisfied before instancing

并且虽然实际上没有Generic的实例.

>编译器不知道Empty的语义(因此也不知道没有创建Generic.Nested的实例)
>和主要问题:您确实想创建IEnumerabe< Generic<> .Nested>的实例,该实例也将是带有“不满意的类型参数”的类型

标签:type-parameter,inner-classes,generics,c
来源: https://codeday.me/bug/20191118/2030933.html