2016-10-26 14 views
0

コードにBackgroundWorkerがあるとします。私は最初に無名関数/代理人を渡したいと思います。ラムダ式/匿名メソッドをBackgroundWorkerに渡す

BackgroundWorker bw = new BackgroundWorker(); 
bw.DoWork += (object sender, DoWorkEventArgs e) => { 
    Func<string> f = (Func<string>)e.Argument; 
    f("step one"); 
    ... 
    f("step two"); 
} 
bw.RunWorkerAsync((string txt) => {Console.WriteLine(txt);}); // doesn't work 
// bw.RunWorkerAsync(delegate(string txt) { Console.WriteLine(txt); })); // doesn't work too 

エラー:

Cannot convert anonymous method to type 'object' because it is not a delegate type

それとも

Cannot convert lambda expression to type 'object' because it is not a delegate type

だから私は、ラムダ式をpassintoする方法/匿名メソッドをBackgroundWorkerにコード怒鳴るは、私が何をしたいのですか?私は「

Action<string> action = (string txt) => Console.WriteLine(txt); 
bw.RunWorkerAsync(action); 

注:

void func(char *ch) 
{ 
    printf("%s", ch); 
} 

void test(void (* f)(char *)) 
{ 
    f("blabla"); 
} 


int main(int argc, char *argv[]) 
{ 
    test(func); 
    return 0; 
} 
+0

[メソッドのパラメータとしてC#パスラムダ式]の可能な重複(http://stackoverflow.com/questions/14297633/c-sharp-pass-lambda- expression-as-method-parameter) – Enfyve

+0

あなたのコードには、文字列で呼び出す 'Func f'型があります。 'f'は何も取らず文字列を返す関数なので、これはコンパイルされません。 'Action f'が必要です。 – Sean

+0

変数に代入し、パラメータとして渡す 'Action obj = Console.WriteLine; bw.RunWorkerAsync(obj); 'はい、' Action '' Func ' – Semuserable

答えて

2

あなたは変数にラムダを割り当て、その後にそれを渡す必要があります。ここでは

は、Cのコードが、私は必要なものを正確に記述することですあなたのコードがデータを取って何も返さないので、 Action<>を使用しました。あなたの DoWorkハンドラが間違っているとこのようにする必要があります:

bw.DoWork += (object sender, DoWorkEventArgs e) => { 
    Action<string> f = (Action<string>)e.Argument; 
    f("step one"); 
    ... 
    f("step two"); 
} 
+1

ではありません。そして、はい、私は 'Func 'と書いています。 – folibis

関連する問題