C#反映具有可变数量类型参数的类型

Dar*_*lus 2 c# generics reflection

是否有可能在运行时获得具有可变数量类型参数的泛型类的类型?

即,基于数字,我们可以得到具有这么多元素的元组类型吗?

Type type = Type.GetType("System.Tuple<,>");

Sal*_*iti 6

写的方式是

Type generic = Type.GetType("System.Tuple`2");
Run Code Online (Sandbox Code Playgroud)

泛型类型的格式很简单:

"Namespace.ClassName`NumberOfArguments"
Run Code Online (Sandbox Code Playgroud)

`是人物96.(ALT + 96).

但是我会避免使用字符串,它比使用typeof或更好的数组查找慢.我会提供一个快速数千倍的静态函数...

private static readonly Type[] generictupletypes = new Type[]
{
    typeof(Tuple<>),
    typeof(Tuple<,>),
    typeof(Tuple<,,>),
    typeof(Tuple<,,,>),
    typeof(Tuple<,,,,>),
    typeof(Tuple<,,,,,>),
    typeof(Tuple<,,,,,,>),
    typeof(Tuple<,,,,,,,>)
};

public static Type GetGenericTupleType(int argumentsCount)
{
    return generictupletypes[argumentsCount];
}
Run Code Online (Sandbox Code Playgroud)