Calling a method on a static class given its type name and method names as strings

后端 未结 5 365
旧时难觅i
旧时难觅i 2020-12-08 10:15

How could I go about calling a method on a static class given the class name and the method name, please?

For example:

Given System.Environment

5条回答
  •  广开言路
    2020-12-08 11:03

    First you need to get the Type (by iterating on the assembly using reflection)

    see this link for details: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx

    or use

    Assembly.GetType
    

    once you have the type in hand you can iterate over members using reflection or

    MethodInfo method = typeof(MyClass).GetMethod("MyMethod");
    

    then you can use MethodInfo.Invoke and pass arguments to invoke the method when you want to invoke it.

提交回复
热议问题