2014-06-13 92 views
0

您好我目前正在嘗試將方法(無返回值)作爲參數傳遞給另一個方法(以便可以從方法中調用它們)。作爲參數的變量參數列表的C#方法

我現在遇到的問題是,我在參數列表中使用Action,因此需要準確定義此方法採用哪些參數。

因此,問題是:有什麼辦法可以省略這個嗎?因此,我不必在參數聲明中精確定義該方法的哪些參數?

Codeexample:

public void A(int myint) 
{ 
    Console.WriteLine(myint.ToString()); 
} 

public void B(int myint1, int myint2) 
{ 
    Console.WriteLine((myint1 + myint2).ToString()); 
} 


public void myQuestionMethod(Action<int> parameterMethod) 
{ 
    //....Dosomething special by creating the parameters within and calling the given methods 
} 


myQuestionMethod(A); 
myQuestionMethod(B); 

因此Aciton parameterMethod可以是被別的東西,讓我給方法作爲誰擁有不同的參數,參數取代?

編輯: 我忘了提及的參數的類型也不固定。

這樣一個函數C可以與(INT參數1,字符串參數2)

+0

是'myQuestionMethod (動作 parameterMethod)'你在找什麼對於?你的問題有點不清楚。 – Stijn

+0

這就是我必須在myQuestionMethod的參數列表中聲明參數(函數)的方法。行動我只在那裏提到,作爲展示我迄今爲止如何使用它的methodToBeCalled參數爲1,參數類型只有1個。 – Thomas

回答

3

號存在,沒有辦法與Action代表要做到這一點(這就是爲什麼有16個過載)。

你可以選擇,如果變量都是同一類型的,並具有相同的含義,創建一個整數數組:

public void A(params int[] myint) 
{ 
} 

public void myQuestionMethod(Action<int[]> parameterMethod) 
{ 
    //....Dosomething special by creating the parameters within and calling the given methods 
} 
+0

我更新了questoin(tnx,用int []指出)。我無法確定參數的類型是否相同(Action本身也不是必需的,我只在示例代碼中提到它,因爲它是迄今爲止用於固定數量參數的變體) – Thomas

+0

我有一個類似的答案,只有一個params數組:public void A(params int [] myInts) –

+0

@ Dennis_E:非常好的一點!更新了我的答案。 –

0

根據你的方法有多大,你可以去只是Action和使用匿名方法,而不是明確地定義的功能

public void myQuestionMethod(Action parameterMethod) 
{ 
    // 
} 
... 
myQuestionMethod(() => Console.WriteLine(myInt.ToString())); 
myQuestionMethod(() => Console.WriteLine((myInt1 + myInt2).ToString())); 
+0

我糾正那裏,當它們作爲參數傳遞時,會啓動方法嗎? (是否有可能使它不是直接啓動,而只是在以後的myQuestion方法中)? – Thomas

+0

@ThomasE。沒有方法在傳遞時不會執行,只是聲明方法的主體,只有在方法內部顯式調用'parameterMethod'時纔會執行該方法。 – James

+0

是否有可能在啓動之前向該方法添加參數? (因此在myQuestionMethod中) – Thomas

0

一種解決方案將是使用反射。除非你沒有任何其他選擇(指定使用其名稱的方法應該避免可能的話)也當然不使用它:

public class Foo 
{ 
    public void A(int myint) 
    { 
     Console.WriteLine(myint.ToString()); 
    } 

    public void B(int myint1, int myint2) 
    { 
     Console.WriteLine((myint1 + myint2).ToString()); 
    } 

    public void myQuestionMethod(string parameterMethodName, params object[] parameters) 
    { 
     var method = this.GetType().GetMethod(parameterMethodName, BindingFlags.Instance | BindingFlags.Public); 
     method.Invoke(this, parameters); 
    } 
} 

public class Test 
{ 
    public static void Main() 
    { 
     var foo = new Foo(); 

     foo.myQuestionMethod("B", 1, 2); 

     Console.Read(); 
    } 
}