从字符串调用动态方法

问题描述 投票:2回答:3

我试图从动态调用方法而不知道它的名字。我很难用英语解释这个,所以有代码:

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文件夹中并加载它并执行它。它适用于动态(我有这样的词典:Dictionnary<string, dynamic> instances;)。我希望应用程序从库中获取方法名称(使用instances["topkek"].GetMethods();,我已经创建了此方法),然后使用它返回的字符串调用该方法。我不知道我说的是什么意思(我是法国人:/)......

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

c# dynamic methods reflection
3个回答
3
投票

你可以按如下方式编写你的方法 -

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

1
投票

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

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

0
投票

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

在您的情况下,调用者(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在评论中的进一步发展。他建议使用代表。

© www.soinside.com 2019 - 2024. All rights reserved.