C#根据函数名称执行对应的函数
时间: 2023-08-16 16:08:39 浏览: 54
可以使用反射来实现根据函数名称执行对应的函数。具体操作如下:
1. 获取类型信息
使用 `Type.GetType` 方法获取要执行的函数所在的类型信息,例如:
```csharp
Type type = Type.GetType("命名空间.类名");
```
2. 获取方法信息
使用 `Type.GetMethod` 方法获取要执行的函数的方法信息,例如:
```csharp
MethodInfo method = type.GetMethod("方法名");
```
3. 执行方法
使用 `MethodInfo.Invoke` 方法执行获取到的方法信息,例如:
```csharp
object result = method.Invoke(null, 参数);
```
其中,第一个参数是要执行的对象,如果方法是静态的,则传入 `null`;第二个参数是要传入方法的参数。
完整示例代码:
```csharp
using System;
using System.Reflection;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Type type = Type.GetType("命名空间.类名");
MethodInfo method = type.GetMethod("方法名");
object result = method.Invoke(null, 参数);
Console.WriteLine(result);
}
}
}
```