使用动态而不是反射来按名称调用方法 [英] Using Dynamic instead of reflection to call method by name

查看:49
本文介绍了使用动态而不是反射来按名称调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.NET-4.0,如何在不使用反射的情况下使用Dynamic完成以下任务?

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);
    }

推荐答案

C#中的动态键入不提供此功能-仍必须在编译时知道要访问的成员的名称. (您当然可以自己创建呼叫站点,并使用DLR的其余机制来解决问题,但这不会比使用反射更简单,并且实际上也不会使用 language 功能.)

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.)

这篇关于使用动态而不是反射来按名称调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆