我想知道是否有办法构建一个可以接受多个泛型参数的类 在编译时不知道
class Something<T,V,U>
此示例显示了一个在运行时期望接收3个泛型参数的类。 我正在寻找一种方法来指定一个除了不同数量的多个参数之外的类
中的某些内容
class Something<T[]>
我以后可以使用反射曝光
Type [] types = GetType().GetGenericArguments();
答案 0 :(得分: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 { }
...
基类(在此示例中没有泛型的class Something
)将为您提供一些可供参考的内容,以及一个尽可能多地集中代码的地方。
根据您的恶意,您最终可能会编写大量冗余代码,在这种情况下,您应该重新考虑使用泛型。
答案 1 :(得分:2)
你可以做一些课 - 一种
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();
获取(传递)动态类型列表 - 不确定它是最好的方式