コードに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;
}
[メソッドのパラメータとしてC#パスラムダ式]の可能な重複(http://stackoverflow.com/questions/14297633/c-sharp-pass-lambda- expression-as-method-parameter) – Enfyve
あなたのコードには、文字列で呼び出す 'Func f'型があります。 'f'は何も取らず文字列を返す関数なので、これはコンパイルされません。 'Action f'が必要です。 –
Sean
変数に代入し、パラメータとして渡す 'Action obj = Console.WriteLine; bw.RunWorkerAsync(obj); 'はい、' Action '' Func ' –
Semuserable