C#中将字符串中的路径转换为可调用的对象
时间: 2024-03-27 08:40:41 浏览: 20
在C#中,可以使用反射来将字符串中的路径转换为可调用的对象。具体来说,可以使用Type类的静态方法GetType来获取类的Type对象,然后使用该对象的GetMethod方法来获取方法的MethodInfo对象,最后使用Invoke方法来调用该方法。
下面是一个示例代码:
```csharp
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
string className = "MyNamespace.MyClass";
string methodName = "MyMethod";
Type type = Type.GetType(className);
if (type == null)
{
Console.WriteLine("Class not found: " + className);
return;
}
MethodInfo method = type.GetMethod(methodName);
if (method == null)
{
Console.WriteLine("Method not found: " + methodName);
return;
}
object result = method.Invoke(null, null);
Console.WriteLine(result);
}
}
namespace MyNamespace
{
class MyClass
{
public static string MyMethod()
{
return "Hello, world!";
}
}
}
```
在这个示例中,我们将字符串"MyNamespace.MyClass"和"MyMethod"转换为实际的类和方法,并调用该方法。输出应该是"Hello, world!"。