Using Dynamic instead of reflection to call method by name

旧城冷巷雨未停 提交于 2019-12-23 08:33:09

问题


Using .NET-4.0, how would I use Dynamic to accomplish the following without using reflection?

     public void InvokeMethod(string methodName)
    {
        Type t = typeof(GCS_WebService);
        GCS_WebService reflectOb = new GCS_WebService();
        MethodInfo m = t.GetMethod(methodName);
        m.Invoke(reflectOb, null);
    }

回答1:


Dynamic typing in C# doesn't provide for that - the names of the members you want to access still has to be known at compile-time. (You could create the call site yourself of course and use the rest of the machinery of the DLR to resolve things, but it wouldn't be any simpler than using reflection, and it wouldn't really be using the language features.)




回答2:


The open source framework Impromptu-Interface has methods the automate all the plumbing to use the DLR to resolve really late like this. It runs 70% faster than reflection with void returning methods.

  public void InvokeMethod(string methodName)
    {
        var reflectOb = new GCS_WebService();
        Impromptu.InvokeMemberAction(reflectOb, methodName)
    }


来源:https://stackoverflow.com/questions/5358224/using-dynamic-instead-of-reflection-to-call-method-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!