为元组制作通用类型

Cra*_*g D 4 c# generics reflection tuples

我已经明确地建立了如何在预先知道项目数量的情况下如下制作通用元组...

        Type t = typeof(Tuple<,,>);
        Type[] keys = new Type[] { typeof(string), typeof(string), typeof(int) };
        Type specific = t.MakeGenericType(keys);
Run Code Online (Sandbox Code Playgroud)

但是如果"keys"数组中的对象数量是可变的呢?如何以初始分配到"t"开始滚动球?

干杯.克雷格

Jon*_*eet 8

就个人而言,我将有一个泛型类型定义的数组:

Type[] tupleTypes = {
    typeof(Tuple<>),
    typeof(Tuple<,>),
    typeof(Tuple<,,>),
    typeof(Tuple<,,,>),
    typeof(Tuple<,,,,>),
    typeof(Tuple<,,,,,>),
    typeof(Tuple<,,,,,,>),
    typeof(Tuple<,,,,,,,>),
};
Run Code Online (Sandbox Code Playgroud)

可以在代码中做到这一点,但这会有点痛苦......可能是这样的:

Type[] tupleTypes = Enumerable.Range(1, 8)
                              .Select(x => Type.GetType("System.Tuple`" + x)
                              .ToArray();
Run Code Online (Sandbox Code Playgroud)

或者避免使用数组:

Type generic = Type.GetType("System.Tuple`" + keys.Length);
Type specific = generic.MakeGenericType(keys);
Run Code Online (Sandbox Code Playgroud)