Reputation: 7908
I'm trying to create a Standard library with common types for WPF/UWP etc.
Since many types are not in Standard, sometimes you have to use reflection.
In this connection, the task of creating a DispatchedHandler from an Action arose.
In UWP, this is easy: new DispatchedHandler(action);
.
But in Standard I only have Type from DispatchedHandler.
private object GetDispatchedHandler(Action action)
{
// Some code
dispatchedHandlerType = windowsAssembly.GetType("Windows.UI.Core.DispatchedHandler");
// Next, you need to transform the `action` and return it from the method.
return Activator.CreateInstance(dispatchedHandlerType, action);
}
This code throws an exception: "Constructor on type 'Windows.UI.Core.DispatchedHandler' not found".
But can get a constructor from a type: dispatchedHandlerType.GetConstructors()[0]
.
The constructor has the following signature: {Void .ctor(System.Object, IntPtr)}
.
The first parameter, I think, should be passed action
.
What should be passed as the second parameter?
dispatchedHandlerConsructor.Invoke(new object[] { action, ??? });
Upvotes: 1
Views: 69
Reputation: 1062502
DispatchedHandler is a delegate type. It doesn't take an Action; it basically is the same thing as Action, but in an incompatible delegate type. The parameters here are the target instance and the function-pointer. You can create arbitrary delegate instances via Delegate.CreateDelegate. Usually you would create this type directly from a target method and instance, and never create the Action, however in this case you may also be able to simply pass in the .Target and .Method from the Action into your call to Delegate.CreateDelegate, since the signature is the same:
var del = Delegate.CreateDelegate(dispatchedHandlerType, action.Target, action.Method);
Upvotes: 3