如何传递多个泛型参数

本文关键字:泛型 参数 何传递 | 更新日期: 2023-09-27 18:03:48

我想知道是否有一种方法来构建一个可以接受多个泛型参数的类在编译时不知道的

   class Something<T,V,U> 

这个例子展示了一个类,它期望在运行时接收3个泛型参数。我正在寻找一种方法来指定一个类,除了多个不同数量的参数

一行的东西
    class Something<T[]> 

之后我可以使用反射

来暴露它
  Type [] types = GetType().GetGenericArguments(); 

如何传递多个泛型参数

不能指定一个未知的泛型数量。你所能得到的最接近的是定义所有可能的变化,或者至少是你愿意处理的。我也建议使用抽象基类。例如:

public abstract 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 { }
...

当您需要引用类型但不知道泛型参数的数量时,抽象类非常有用。

根据你的不良意图,你可能会在使用这种解决方案时写很多多余的代码,在这种情况下,你应该重新考虑你对泛型的使用。

你可以创建一些类——一种

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());
    }
}

并将其用作

var list = T<int, T<string, int[]>>.GetTypeCombination().ToList();

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