CSharp根据方法名调用方法

faith team

在实际开发中有需要通过string方法名去调用方法的操作

使用反射原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace Faith.Console6
{
public class Program
{
public static void Main(string[] args)
{
//命名空间+类名
string className = "Faith.Console6.Program";
//方法名
string methodName = "hello01";
//参数
Object[] paras = new object[] { 1, "faith" };
Type t = Type.GetType(className);
object obj = Activator.CreateInstance(t);
//调用
var method =t.GetMethod(methodName);
method.Invoke(obj, paras);
Console.ReadLine();
}
public void hello(int index,string name){
Console.WriteLine("hello world!" + index + name);
}
}
}

运行截图
Test

  • Title: CSharp根据方法名调用方法
  • Author: faith team
  • Created at: 2023-06-29 10:38:05
  • Updated at: 2025-11-29 09:01:08
  • Link: https://redefine.ohevan.com/2023/06/29/20230629CSharp根据方法名调用方法/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments
On this page
CSharp根据方法名调用方法