How to run any method knowing only its full name

I have a method name: "Garden.Plugins.Code.Beta.Business.CalculateRest"

How do I start it? I am thinking of this fantastic reflection based solution like RunMethod (string MethodName)

0


source to share


4 answers


  • Separate it by the type name and the method name by separating it by the last dot
  • Get the type using Type.GetType or Assembly.GetType . (Type.GetType will only show up in the currently executing assembly and mscorlib unless you supply the assembly name in the argument.)
  • Get a method from a type using Type.GetMethod . Assuming this is a public static method, specify BindingFlags.Public | BindingFlags.Static

    .
  • Execute the method by calling MethodInfo.Invoke (null, null). (The first null indicates "no target", that is, a static method, the second does not specify any arguments.)


If you want to call an instance method or one that takes parameters, you will also need to figure out how to get this information.

+3


source


It's not as easy as treating everything to the left of the last dot as a literal name. If you have a form type:

XYZType

then this is not necessarily the case when X, Y and Z are namespaces. They can also be the types themselves, and the subsequent parts can be inner classes:



class X
{
  class Y
  {
   // etc
  }
}

      

If so, then Type.GetType ("X.YU") won't resolve class Y. Instead, clr separates inner classes with a +, so you really need to call Type.GetType ("X + Y");

If the method you are calling is parameters , then you need some extra work. You need to flip the variable parameters into an array and pass that. You can check the variable parameters by grabbing the ParameterInfo data for the method and see if the last ParamArray parameter is included .

+2


source


It will be slow, trust me. So don't put it in a critical place.

Other than that, you just need to do it "manually". Start listing through all the namespaces, classes, etc., until you find what you need. I don't think there is anything out of the ordinary that has been done in advance. (Although I haven't searched)

+1


source


If type is instance type:

Type.GetType("Garden.Plugins.Code.Beta.Business")
    .GetMethod("CalculateRest").Invoke(myInstanceOfTheType, param1, param2);

      

If it's a static method:

Type.GetType("Garden.Plugins.Code.Beta.Business")
    .GetMethod("CalculateRest").Invoke(null, param1, param2);

      

If it doesn't accept parameters, just leave "param1, param2, etc." ...

+1


source







All Articles