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

后端 未结 5 358
旧时难觅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 10:51

    What you are doing here is reflecting on the type named Environment and using the GetPropery and GetGetMethod methods to get the get method of the Environment.CurrentDirectory property like so;

    var getMethod = typeof(Environment).GetProperty("CurentDirectory", BindingFlags.Public | BindingFlags.Static).GetGetMethod();
    var currentDirectory = (string)getMethod.Invoke(null, null);
    

    Calling the get method of a property returns it's value and is equivilent to;

    var value = Environment.CurrentDirectory;
    

提交回复
热议问题