How to convert delegate to identical delegate?

后端 未结 5 2039
你的背包
你的背包 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:08

    Thomas Levesque's answer does not work well for some special cases. This is an improved version.

    public static Delegate ConvertDelegate(this Delegate src, Type targetType, bool doTypeCheck)
    {
        //Is it null or of the same type as the target?
        if (src == null || src.GetType() == targetType)
            return src;
        //Is it multiple cast?
        return src.GetInvocationList().Count() == 1
            ? Delegate.CreateDelegate(targetType, src.Target, src.Method, doTypeCheck)
            : src.GetInvocationList().Aggregate
                (null, (current, d) => Delegate.Combine(current, ConvertDelegate(d, targetType, doTypeCheck)));
    }
    

    The benefit of the above code is it passes the following test

    EventHandler e = (o,e)=>{}
    var a = e.ConvertDelegate(typeof(Action), true);
    Assert.AreEqual(e, e.ConvertDelegate(typeof(EventHandler), true));
    

    whilst

    EventHandler e = (o,e)=>{}
    var a = new Action(e);
    Assert.AreEqual(e, new EventHandler(a));
    

    will fail.

提交回复
热议问题