可变数量的方法参数,每个参数具有不同的类型
本文关键字:参数 类型 方法 | 更新日期: 2023-09-27 18:35:32
编辑:
func(params dynamic[] parameters)
{
}
允许它接受具有变量类型的变量参数。无知不是幸福。
问题:
我需要编写一个方法,该方法采用 n 个不同类型的列表,例如:
List<Type1> list1 = .....;
List<Type2> list2 = .....;
List<TypeN_1> listN_1 = .....;
List<TypeN> listN = .....;
var result=func(list1,list2,listN);
但我无法使用"params"关键字进行管理,因为它不会让内部函数知道每个列表
public int func< ? ? >(? ? ? ?)
{
int result=0;
... get all lists and put them in some function:
innerFunc(list1);
// which is declared as innerFunc<T>(List<T> p){}
return result;
}
你真的需要这样的功能吗?也许你可以写一个函数,一次处理两个列表,生成一个新列表。
List<C> Combine<A,B,C>(List<A>, List<B>, Func<A,B,C>)
然后,您可以处理多个列表。
Combine(Combine(Combine(a, b, f1), c, f2), d, f3);
Combine(a, Combine(b, Combine(c, d, f1), f2), f3);
如果没有更多的上下文,我不能说这对你的问题是否可行。
具有不同泛型类型参数的列表的最大公分母是IList
int func(params IList[] parameters)
{
}
然后,您可以使用
Type t = parameters[i].GetType();
if (t.IsGenericType)
{
Type typeArgument = t.GetGenericArguments()[0];
...
请参阅: Type.GetGenericArguments Method ()