简体   繁体   中英

C# Custom Events with Overloads

So I have a custom event like this:

    Work w = new worker()
    w.newStatus += new worker.status(addStatus);
    w.doWork();

    void addStatus(string status)
    {
        MessageBox.Show(status);
    }

and this:

    public event status newStatus;
    public delegate void status(string status);

    public void doWork()
    {
        newStatus("Work Done");    
    }

If I were to make "addStatus" an overload, what would I have to do to pass overload parameters without creating a second delegate/event?

Make your status delegate generic like this:

public event Status<String> NewStatus;
public event Status<Int32> OtherStatus;
public delegate void Status<T>(T status);

public void DoWork()
{
    NewStatus("Work Done");
    OtherStatus(42);
}

Then you can create strongly typed events that use the same delegate.

Edit: Here is a complete example showing this in action:

using System;

class Example
{
    static void Main()
    {
        Work w = new Work();
        w.NewStatus += addStatus;
        w.OtherStatus += addStatus;
        w.DoWork();
    }    
    static void addStatus(String status)
    {
        Console.WriteLine(status);
    }
    static void addStatus(Int32 status)
    {
        Console.WriteLine(status);
    }
}

class Work
{
    public event Status<String> NewStatus;
    public event Status<Int32> OtherStatus;
    public delegate void Status<T>(T status);

    public void DoWork()
    {
        NewStatus("Work Done");
        OtherStatus(42);
    }
}
    void addStatus(string status, int something)
or
    void addStatus(int status)
or
    void addStatus()
should all work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM