可以为任何对象方法创建自定义事件吗?
为此,我仅使用以下语法?

myObject.myMethod +=new EventHandler(myNameEvent);

以下代码提示了这个问题:
   private void btRunProcessAndRefresh_Click(object sender,EventArgs e)
    {
        myProcess =new Process();
        myProcess.StartInfo.FileName = @"c:\ConsoleApplication4.exe";
        myProcess.Exited += new EventHandler(MyProcessExited);
        myProcess.EnableRaisingEvents =true;
        myProcess.SynchronizingObject =this;
        btRunProcessAndRefresh.Enabled =false;
        myProcess.Start();
    }

最佳答案

是的,您可以这样做:

Creating advanced C# custom events

或者

The Simplest C# Events Example Imaginable

public class Metronome
{
    public event TickHandler Tick;
    public EventArgs e = null;
    public delegate void TickHandler(Metronome m, EventArgs e);
    public void Start()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
}
public class Listener
{
    public void Subscribe(Metronome m)
    {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e)
    {
        System.Console.WriteLine("HEARD IT");
    }
}
class Test
{
    static void Main()
    {
        Metronome m = new Metronome();
        Listener l = new Listener();
        l.Subscribe(m);
        m.Start();
    }
}

关于c# - 创建自定义事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9885437/

10-17 01:06