C#获取方法并调用它
示例
获取实例方法并调用它
using System;
public class Program
{
public static void Main()
{
var theString = "hello";
var method = theString
.GetType()
.GetMethod("Substring",
new[] {typeof(int), typeof(int)}); //方法参数的类型
var result = method.Invoke(theString, new object[] {0, 4});
Console.WriteLine(result);
}
}输出:
地狱
观看演示
获取静态方法并调用它
另一方面,如果该方法是静态的,则不需要实例来调用它。
var method = typeof(Math).GetMethod("Exp");
var result = method.Invoke(null, new object[] {2});//将null作为第一个参数传递(不需要实例)
Console.WriteLine(result); //你会得到e^2输出:
7.38905609893065
观看演示
热门推荐
10 读书祝福语女生短句简短
11 感谢同事新婚祝福语简短
12 感谢教官文案祝福语简短
13 员工聚会蛋糕祝福语简短
14 元宵发客户祝福语简短
15 给团队信心祝福语简短
16 医美的祝福语大全简短
17 异国姻缘的祝福语简短
18 兄妹拍照祝福语简短的话