从字符串调用动态方法

Call dynamic method from string

我试图在不知道名称的情况下从动态调用方法。我很难用英语解释这个所以有代码:

public void CallMethod(dynamic d, string n)
{
    // Here I want to call the method named n in the dynamic d
}

我想要这样的东西:d.n() 但是 n 被字符​​串替换了。

我想要这个:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

但具有 动态

如果您需要上下文来帮助您:我正在制作一个支持 "mods" 的应用程序,您将 DLL 放在 mod 文件夹中,它会加载并执行它。它适用于 dynamic(我有一个这样的字典:Dictionnary<string, dynamic> instances;)。我希望应用程序从库中获取方法名称(使用 instances["topkek"].GetMethods();,我已经制作了此方法),然后使用字符串 returns 调用该方法。我不知道我说的是否有意义(我是法国人:/)...

我正在使用 VS 2013 Express 和 .Net framework 4.5,如果你需要更多信息来帮助我,请问我。

如果所有方法都是无效的,这可能会起作用。否则你需要稍微改变一下。

    public void CallMethod(string className, string methodName)
    {
        object dynamicObject;
        // Here I want to call the method named n in the dynamic d
        string objectClass = "yourNamespace.yourFolder." + className;
        Type objectType = Type.GetType(objectClass);
        if (objectType == null)
        {
            // Handle here unknown dynamic objects
        }
        else
        {
            // Call here the desired method
            dynamicObject = Activator.CreateInstance(objectType);
            System.Reflection.MethodInfo method = objectType.GetMethod(methodName);
            if (method == null)
            {
                // Handle here unknown method for the known dynamic object
            }
            else
            {
                object[] parameters = new object[] { };   // No parameters
                method.Invoke(dynamicObject, parameters);
            }
        }
    }

你可以这样写你的方法 -

public void CallMethod(dynamic d, string n)
    {
        d.GetType().GetMethod(n).Invoke(d, null);
    }

我想添加另一种方法作为解决方案:

在您的情况下,调用者(mod 的开发者)知道要调用的方法。因此,这可能会有所帮助:

// In the main application:
public dynamic PerformMethodCall(dynamic obj, Func<dynamic, dynamic> method)
{
    return method(obj);
{


 // In a mod:
 mainProgram.PerformMethodCall(myDynamicObj, n => n.myDynamicMethod());

 // In another mod:
 mainProgram.PerformMethodCall(myDynamicObj, n => n.anotherMethod());

这是 Yuval Itzchakov 在他的评论中的想法的进一步发展。他曾建议使用委托人。