如何传递多个泛型参数

era*_*zap 5 .net c# generics reflection

我想知道是否有一种方法来构建一个可以接受多个通用参数的类,这些参数在编译时是未知的

   class Something<T,V,U> 
Run Code Online (Sandbox Code Playgroud)

此示例显示了一个类,它希望在运行时接收3个泛型参数.我正在寻找一种方法来指定一个除了多个不同数量的参数之外的类

沿着这条线的东西

    class Something<T[]> 
Run Code Online (Sandbox Code Playgroud)

我后来可以用反射曝光

  Type [] types = GetType().GetGenericArguments(); 
Run Code Online (Sandbox Code Playgroud)

Kei*_*ith 7

您不能指定未知数量的泛型.您可以获得的最接近的是定义所有可能的变体,或者至少与您愿意处理的变量一样多.

public class Something { }
public class Something<T1> : Something { }
public class Something<T1, T2> : Something { }
public class Something<T1, T2, T3> : Something { }
public class Something<T1, T2, T3, T4> : Something { }
public class Something<T1, T2, T3, T4, T5> : Something { }
...
Run Code Online (Sandbox Code Playgroud)

基类(class Something在这个例子中没有泛型)将为您提供引用的通用内容以及集中尽可能多的代码的位置.

根据您的恶意,您最终可能会编写大量冗余代码,在这种情况下,您应该重新考虑使用泛型.


Dan*_*Nsk 3

你可以做一些课程 - 一种

public static class TypeHelper
{
    public static IEnumerable<Type> GetTypeCombination(this Type type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(T<,>))
            return type.GetGenericArguments().SelectMany(GetTypeCombination);

        return new Type[] { type };
    }
}

public class T<T1, T2>
{
    public static IEnumerable<Type> GetTypeCombination()
    {
        return typeof(T1).GetTypeCombination()
            .Concat(typeof(T2).GetTypeCombination());
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其用作

var list = T<int, T<string, int[]>>.GetTypeCombination().ToList();
Run Code Online (Sandbox Code Playgroud)

获取(传递)类型的动态列表 - 不确定这是最好的方法