2015-03-03 75 views
0

我遇到了問題。我只知道如何使用動作和func,但問題是我需要把一個方法放入這樣的構造函數中。如何將一個方法添加到構造函數中?

Reader read = new Reader(1000, cki, method); 

但問題是,該方法需要這樣的輸入。

public static void method(int Integer) 

我在那種情況下做什麼?

+0

閱讀:http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp – 2015-03-03 13:10:28

回答

2

您可以使用的Action構造parameter.The返回類型的Action<int>void和通用的說法是參數type.So它與你的方法,它需要一個int並返回void匹配。

+0

它與工作? – Hui 2015-03-03 13:00:27

+0

它說參數3:不能從'方法組'轉換爲'System.Action' – Hui 2015-03-03 13:03:04

+0

既不能與字符串一起工作 – Hui 2015-03-03 13:06:08

0

不能使用的方法,但你可以使用一個動作

public Reader(int first, object cki, Action method) 
{ 
    //ctor code here 
    method.Invoke(); 
} 

不是使用:

var reader = new Reader(1000, cki,() => SomeMethod(123)); 
+0

我知道。但它對我沒有任何好處 – Hui 2015-03-03 13:01:04

+0

你到底在做什麼?你不能傳遞一個方法。 – Darek 2015-03-03 13:01:30

+0

是的,我看到參數3:不能從'方法組'轉換爲'System.Action' – Hui 2015-03-03 13:03:13

0

看來你正在尋找Action<int>和withing像構造函數中調用它以下?

using System; 

public class Program 
{ 
    public static void Main() 
    { 
     Sample s = new Sample((i) => {Console.WriteLine(i);}); 
    } 
} 

public class Sample 
{ 
    public Sample(Action<int> method) 
    { 
     method(5); 
    } 
} 
相關問題