0

我正在尝试学习委托的用法,我见过的所有代码示例都使用参数传递给内部方法,

该示例的目标是在不传递参数的情况下在表单启动时打开 2 个消息框这是我尝试过的代码,但我不知道如何调用内部函数

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace Messageboxes2
{
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        Delegation delegated = new Delegation();
        delegated.
    }

}
class Delegation
{    
    public delegate string mbox ();

    static void msgboz1(mbox d)
    {
        MessageBox.Show("1rstBox");
    }
    static void msbox2(mbox d)
    { 
        MessageBox.Show("2ndbox");
    }
}
}

谢谢您的帮助

4

2 回答 2

0

Simply passing delegate as a parameter does not call the method. You better learn more about delegates, you can try following for better understanding.

public partial class MainForm : Form
{
public MainForm()
{
    InitializeComponent();
    Delegation.Invoke(Delegation.msgboz1);
    Delegation.Invoke(Delegation.msbox2);
}

}
class Delegation
{    
public delegate void mbox ();

public static void msgboz1()
{
    MessageBox.Show("1rstBox");
}
public static void msbox2()
{ 
    MessageBox.Show("2ndbox");
}
public static void Invoke(mbox method)
{ 
    method();
}
}

EDIT: You can use BeginInvoke method to call methods asynchronously.

class Program
{
    static void Main(string[] args)
    {
        Delegation.MethodCaller mc1 = new Delegation.MethodCaller(Delegation.Method1);
        Delegation.MethodCaller mc2 = new Delegation.MethodCaller(Delegation.Method2);
        mc1.BeginInvoke(null, null);
        mc2.BeginInvoke(null, null);
        Console.ReadLine();
    }

    class Delegation
    {
        public delegate void MethodCaller();

        public static void Method1()
        {
            Console.WriteLine("Method 1 Invoked");
            Thread.Sleep(2000);
            Console.WriteLine("Method 1 Completed");
        }
        public static void Method2()
        {
            Console.WriteLine("Method 2 Invoked");
            Thread.Sleep(2000);
            Console.WriteLine("Method 2 Completed");
        }
    }
}
于 2012-06-08T10:16:43.537 回答
0

首先从这两种方法中删除参数。然后,如果您了解 lambda 表达式,那么:

mbox myMboxDelegate = new mBox(() =>
{
   msgboz1();
   msbox2();
});

myMBoxDelegate();

或尝试:

mbox myMboxDelegate = new mBox();
myMboxDelegate += msgboz1();
myMboxDelegate += msbox2();
myMboxDelegate();
于 2012-06-08T10:22:34.940 回答