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

Using a class nested in a generic class as type parameter in 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 需要类型参数才能实例化。

我可以用 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 class 不以任何方式使用类型参数:我只是想为了代码组织目的而嵌套定义它。

不,你不能那样做。正如你所说

all the type parameters must be satisfied before instancing

虽然实际上没有生成 Generic<>.Nested 的实例

  • 编译器不知道 Empty 的语义(因此不知道没有创建 Generic<>.Nested 的实例)
  • 主要问题:你确实想创建一个IEnumerabe<Generic<>.Nested>的实例,它是一个类型"unsatisfied type parameters",也是

我认为您的主要目标可能只需将子 class 放在同一个命名空间中父的旁边即可实现。

命名空间实际上应该按照您在 post 下的评论中所说的方式组织代码。

您真的应该只将 class 定义为子 class,只有父 class 会使用它。