简体   繁体   English

方法参数数量可变,每种参数类型不同

[英]Variable number of method parameters with different types for each of them

Edit: 编辑:

func(params dynamic[] parameters)
{

}

lets it accept variable parameters with variable types. 让它接受具有可变类型的可变参数。 Ignorance is not bliss. 无知不是幸福。

Question: 题:

I need to write a method that takes n number of lists each of different types such as: 我需要编写一个方法,该方法需要n个不同类型的列表,例如:

 List<Type1> list1 = .....;
 List<Type2> list2 = .....;
 List<TypeN_1> listN_1 = .....;
 List<TypeN> listN = .....;
 var result=func(list1,list2,listN);

but I couldn't manage with "params" keyword because it doesn't let inner functions know < T > of each list. 但是我无法使用“ params”关键字进行管理,因为它无法让内部函数知道每个列表的<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;
 }

Do you truly need such a function? 您真的需要这样的功能吗? Perhaps you can instead write a function which works on two lists at a time, producing a new list. 也许您可以改为编写同时在两个列表上工作的函数,从而生成一个新列表。

List<C> Combine<A,B,C>(List<A>, List<B>, Func<A,B,C>)

Then you can handle multiple lists. 然后,您可以处理多个列表。

Combine(Combine(Combine(a, b, f1), c, f2), d, f3);
Combine(a, Combine(b, Combine(c, d, f1), f2), f3);

Without more context I cannot say whether this is possible for your problem. 没有更多的上下文,我不能说这是否可能解决您的问题。

The greatest common denominator of lists with different generic type parameters is IList 具有不同泛型类型参数的列表的最大公分母是IList

int func(params IList[] parameters)
{
}

You can then get the generic type parameter with 然后,您可以使用

Type t = parameters[i].GetType();
if (t.IsGenericType)
{
    Type typeArgument = t.GetGenericArguments()[0];
    ...

See: Type.GetGenericArguments Method () 请参阅: Type.GetGenericArguments方法()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 具有可变数量参数的匿名方法 - Anonymous method with a variable number of parameters 调用不同变量类型的两个参数? - Invoke With Two Parameters Of Different Variable Types? 修改方法以接受不同数量和类型的参数 - Modifying method to accept different number and type of parameters 通用参数数目可变的C#方法 - c# method with variable number of generic parameters 具有可变数量参数的Java“虚拟”方法 - Java “Virtual” method with variable number of parameters 继承时覆盖具有相同参数但返回类型不同的方法 - Overriding a method with the same parameters, but different return types, when inheriting 如何编写将不同类型作为参数的泛型方法? - How do I write a generic method that takes different types as parameters? 如何创建具有可变参数/不同方法签名的方法接口? - How to create method interface with variable parameters / different method signatures? C#方法可以定义可变数目的对象参数,以及可变数目的整数参数吗? - Can a C# method define a variable number of object parameters, and a variable number on integer parameters? 将不同数字类型作为参数发送给方法时是否存在性能问题? - Are there performance issues on sending different number types as parameter to a method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM