简体   繁体   中英

How can I call method that has a delegate parameter using reflection?

How can I call the method below using reflection?

namespace Awesomium.Core
{
    public delegate JSValue JavascriptMethodHandler(object sender, JavascriptMethodEventArgs e);

    public class JSObject
    {
        public void Bind(string methodName, JavascriptMethodHandler handler)
        {
            // Does something...
        }
    }
}

My progress is below. I get exception on CreateDelegate.

Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

public class AwesomiumHelper
{
    private Func<object, dynamic, dynamic> JavascriptMethodHandlerAction;

    public void RegisterJavascriptMethodAndBind(string methodName, Func<object, dynamic, dynamic> func)
    {
        if (func != null)
        {
            var jsoType = AwesomiumCore.GetExportedTypes().First(f => f.Name == "JSObject");
            var jso = Activator.CreateInstance(jsoType);

            var t = AwesomiumCore.GetTypes().FirstOrDefault(f => f.Name == "JavascriptMethodHandler");

            var mi = typeof(AwesomiumHelper).GetMethod("JavascriptMethodHandlerProxy", BindingFlags.NonPublic | BindingFlags.Instance);

            // GETTING EXCEPTION HERE
            var d = Delegate.CreateDelegate(t, this, mi);
            // GETTING EXCEPTION HERE

            JavascriptMethodHandlerAction = func;

            var mi0 = jsoType.GetMethod("Bind", new[] { typeof(string), t });
            mi0.Invoke(jso, new object[] { methodName, d });
        }
    }

    private dynamic JavascriptMethodHandlerProxy(object sender, dynamic e)
    {
        return JavascriptMethodHandlerAction?.Invoke(sender, e);
    }
}

UPDATE: I solved the problem by creating two libraries. Interface library and class library. Interface library is referenced by the class library and main program. Awesomium is referenced by class library. At runtime I am loading class library by reflection and use its methods which are defined in interface library.

问题是您误解了CreateDelegate的第一个参数-它引用了委托的类型,而不是目标:

var d = Delegate.CreateDelegate(typeof(Func<object, dynamic, dynamic>), this, mi);

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