0

I'm using WPF mvvm pattern anyway if some method got string parameter is this possible calling like

SomeClass1 sc  = new SomeClass();
DummyClass2 dc = new DummyClass2();

public void SomeMethod(string param) //param = "SomeMethodName"
{ 
    sc.'param'(dc);
}

The key is calling class object's fuction via param without branch or Data structure mapping.

maybe using reflection.. any good idea?

  • Anyhow, you shouldn't be required to do this, are you trying to invoke a function when a button is clicked or something, you can use commands for it for example – skjagini Sep 14 '18 at 00:42

1 Answers1

1

Yes that's possible via reflection. You can use the Invoke method.

It would look something like this:

MethodInfo method = type.GetMethod(name); object result = method.Invoke(objectToCallTheMethodOn);

Having said that, in normal circumstances you shouldn't use reflection to call methods in c#. It's only for really special cases.


Here's a full example:

class A 
{
    public int MyMethod(string name) {
        Console.WriteLine( $"Hi {name}!" );
        return 7;
    }
}



public static void Main()
{
    var a = new A();
    var ret = CallByName(a, "MyMethod", new object[] { "Taekyung Lee" } );
    Console.WriteLine(ret);
}

private static object CallByName(A a, string name, object[] paramsToPass )
{
    //Search public methods
    MethodInfo method = a.GetType().GetMethod(name);
    if( method == null )
    {
        throw new Exception($"Method {name} not found on type {a.GetType()}, is the method public?");
    }
    object result = method.Invoke(a, paramsToPass);
    return result;
}

This prints:

Hi Taekyung Lee!
7
tymtam
  • 31,798
  • 8
  • 86
  • 126