How to convert delegate to identical delegate?

后端 未结 5 2052
你的背包
你的背包 2021-02-18 19:04

There are two descriptions of the delegate: first, in a third-party assembly:

public delegate void ClickMenuItem (object sender, EventArgs e)

s

5条回答
  •  粉色の甜心
    2021-02-18 19:24

    Fortunately, it's simple. You can just write:

    ClickMenuItem clickMenuItem = ...; // Wherever you get this from
    EventHandler handler = new EventHandler(clickMenuItem);
    

    And in reverse:

    EventHandler handler = ...;
    ClickMenuItem clickMenuItem = new ClickMenuItem(handler);
    

    This will even work in C# 1.0. Note that if you then change the value of the original variable, that change won't be reflected in the "converted" one. For example:

    ClickMenuItem click = new ClickMenuItem(SomeMethod);
    EventHandler handler = new EventHandler(click);
    click = null;
    
    handler(this, EventArgs.Empty); // This will still call SomeMethod
    

提交回复
热议问题