Why can't I call Delegate.CreateDelegate in my Portable Class Library?

前端 未结 2 1715
既然无缘
既然无缘 2020-12-30 10:01

I have the following problem: I want to call Delegate.CreateDelegate from within my Portable Class Library targeting .NET 4.5, Windows Phone 8 and Windows 8 Sto

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 10:29

    OK, after a night of sleeping I recognized that my question actually should be "How do I dynamically create delegates in the new API introduced with the Windows Runtime?". As Rafael indicated in the comments of my question, different APIs are provided when Windows 8 / Phone 8 is targeted in addition to .NET. If Silverlight is also targeted, then APIs that are not available in Windows 8 / Phone 8 will be mapped and this explains why I can suddenly call Delegate.CreateDelegate when I add Silverlight as a target of the Portable Class Library. In .NET, the new APIs for Reflection were introduced with .NET 4.5.

    Anyway, to create a delegate in Windows 8 / Windows Phone 8, one has to use the MethodInfo.CreateDelegate method, just like this:

    public class MyClass
    {
        public void MyMethod(EventHandler handler)
        {
            var methodInfo = handler.GetMethodInfo();
            var @delegate = methodInfo.CreateDelegate(typeof(OpenEventHandler), null);
        }
    }
    
    public delegate void OpenEventHandler(T target, object sender, EventArgs arguments);
    

提交回复
热议问题