messagebox.show中的Lambda匿名方法

mou*_*ler 0 c# lambda winforms

我只是在玩匿名方法,我想知道为什么这段代码不能编译.Messagebox show需要一个字符串,我试图将它返回一个字符串.

            MessageBox.Show(() => 
            {
                if (button1.Text == "button1")
                {
                   return "ok";
                }
                else
                {
                   return "not button1 text";
                }
            });
Run Code Online (Sandbox Code Playgroud)

无法将lambda表达式转换为字符串类型,因为它不是委托类型.

有人可以解释原因吗?我错过了演员吗?

msp*_*rek 8

你的代码正在做的是定义一个Func返回一个字符串(Func<string>).然后你尝试传递Func<string>MessageBox.Show作为参数.请注意,MessageBox.Show不接受Func<string>类型,它接受string所以你不能以这种方式传递lamda表达式).但你可以这样做:

Func<string> yourFunc = () => 
            {
                if (button1.Text == "button1")
                {
                   return "ok";
                }
                else
                {
                   return "not button1 text";
                }
            };

MessageBox.Show(yourFunc());
Run Code Online (Sandbox Code Playgroud)