簡體   English   中英

方法參數數量可變,每種參數類型不同

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

編輯:

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”關鍵字進行管理,因為它無法讓內部函數知道每個列表的<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;
 }

您真的需要這樣的功能嗎? 也許您可以改為編寫同時在兩個列表上工作的函數,從而生成一個新列表。

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方法()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM