1

这就是我想要实现的

  if( this.BeginInvoke((Action)(
        () => MessageBox.Show("Test", 
                              MessageBoxButtons.YesNo) == DialogResult.No)))

以上给出了错误。我尝试将委托与外部方法分开,例如

delegate void test(string text);
private void SetTest(string text)
{
 if(MessageBox.Show(text,"", MessageBoxButtons.YesNo) == DialogResult.No)

}

但这违反了我需要代表的原因。我发现第一个作品适合我,但我不知道如何将它放在 if/else 语句中。请以更好的方式提供任何帮助,我将不胜感激。

  if(this.BeginInvoke((Action)(
      () => MessageBox.Show("Test", 
                            MessageBoxButtons.YesNo) == DialogResult.No)))
4

3 回答 3

2

It seems like you need an Invoke() method, not BeginInvoke():

var messageBoxResult = (DialogResult)Invoke(new Func<DialogResult>(
    () => MessageBox.Show("Test", "Test", MessageBoxButtons.YesNo)));
if(messageBoxResult == DialogResult.No)
{
}

BeginInvoke executes delegate asynchronously, meaning that the result is not immediately available on the thread which calls BeginInvoke.

于 2013-11-11T03:50:52.217 回答
2

另一个变体......这很丑陋:

if ((bool)this.Invoke((Func<bool>)delegate
  {
  return MessageBox.Show("Test Message", 
                         "Test Title", 
                         MessageBoxButtons.YesNo) == DialogResult.No;
  }))
{
    Console.WriteLine("No was indeed selected.");
}

这应该适用于任何版本的 C#:

private void button1_Click(object sender, EventArgs e)
{
    System.Threading.Thread T = new System.Threading.Thread(Foo);
    T.Start();
}

delegate bool SetTestDelegate(string text);
private bool SetTest(string text)
{
    return (MessageBox.Show(text, "", MessageBoxButtons.YesNo) == DialogResult.No);
}

private void Foo()
{
    if ((bool)this.Invoke(new SetTestDelegate(SetTest), new object[] {"test"}))
    {
        Console.WriteLine("No was indeed selected.");
    }
}

编辑:您可以将该代码重构为更有用的东西......

private void button1_Click(object sender, EventArgs e)
{
    System.Threading.Thread T = new System.Threading.Thread(Foo);
    T.Start();
}

private void Foo()
{
    if (Response("test") == System.Windows.Forms.DialogResult.No)
    {
        Console.WriteLine("No was indeed selected.");
    }
}

delegate DialogResult ResponseDelegate(string text);
private DialogResult Response(string text)
{
    if (this.InvokeRequired)
    {
        return (DialogResult)this.Invoke(new ResponseDelegate(Response), new object[] { "test" });
    }
    else
    {
        return MessageBox.Show(text, "", MessageBoxButtons.YesNo);
    }
}
于 2013-11-11T03:53:04.657 回答
1

Why not make your (and your fellow coders) life easier, and do something like:

var user_said_no = this.BeginInvoke((Action)(
   () => MessageBox.Show("Test", MessageBoxButtons.YesNo) == DialogResult.No));

And then have:

if (user_said_no)
   cancel_nuclear_attack() ; // Or whichever things you need to do.
于 2013-11-11T03:48:58.937 回答