可变数量的方法参数,每个方法参数具有不同的类型

时间:2016-02-21 19:56:39

标签: c#

修改

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”关键字进行管理,因为它不会让内部函数知道&lt; T>每个清单。

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

2 个答案:

答案 0 :(得分:2)

你真的需要这样的功能吗?也许您可以改为编写一个一次在两个列表上工作的函数,生成一个新列表。

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

如果没有更多上下文,我不能说这是否可能导致您的问题。

答案 1 :(得分:1)

具有不同泛型类型参数的列表的最大公分母是IList

int func(params IList[] parameters)
{
}

然后,您可以使用

获取泛型类型参数
Type t = parameters[i].GetType();
if (t.IsGenericType)
{
    Type typeArgument = t.GetGenericArguments()[0];
    ...

请参阅:Type.GetGenericArguments Method ()