Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call dynamic method from string

I'm trying to call a method from a dynamic without knowing its name. I have difficulties to explain this in english so there's the code:

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

I want something like:d.n() but with n replaced by the string.

I want this :

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

but with dynamic.

If you need the context to help you: I'm make an application that's support "mods", you put DLLs in the mod folder and it loads it and execute it. It works with dynamic (I have a dictionnary like this : Dictionnary<string, dynamic> instances;). I want the application to get the methods name from the library (with instances["topkek"].GetMethods();, I've already made this method) but then call the method with the string it returns. I don't know if what I said mean something (I'm french :/ )...

I'm using VS 2013 Express with the .Net framework 4.5, if you need more information to help me ask me.

like image 872
SwagLordKnight Avatar asked Oct 27 '25 06:10

SwagLordKnight


1 Answers

you can write your method as follows -

public void CallMethod(dynamic d, string n)
    {
        d.GetType().GetMethod(n).Invoke(d, null);
    }
like image 73
Sanjay Singh Avatar answered Oct 28 '25 21:10

Sanjay Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!