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 红包祝福语简短10字
18 周六早晨祝福语简短