使用动态而不是反射来按名称调用方法
问题描述:
使用.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.)