从字符串调用动态方法

Swa*_*ght 3 c# reflection methods dynamic

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

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

我想要类似的东西:d.n()但是用字符串替换n

我要这个 :

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
Run Code Online (Sandbox Code Playgroud)

但随着动态.

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

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

San*_*ngh 6

你可以写你的方法如下 -

public void CallMethod(dynamic d, string n)
    {
        d.GetType().GetMethod(n).Invoke(d, null);
    }
Run Code Online (Sandbox Code Playgroud)