反射調用時,必須傳遞所有參數, 無論是否有默認參數。
public class InvokeTarget { public static void Invoke1(int a) { } public static void Invoke2(Action<int> a, int b = 0) { } public void Invoke3() { } } public class Caller { void CallFunction() { // get type, 如果不知道目標類型, 就通過assembly去找,懶得寫了 var @it = typeof(InvokeTarget); // get target var @it2 = new InvokeTarget(); @it.GetMethods().Where(x => x.Name == "Invoke1").ToArray()[0] .Invoke(@it, new object[] { 1 }); // 必須傳完整參數列表 @it.GetMethods().Where(x => x.Name == "Invoke2").ToArray()[0] .Invoke(@it, new object[] { new Action<int>(Invoke2CallBack), 3 }); @it.GetMethods().Where(x => x.Name == "Invoke3").ToArray()[0] .Invoke(@it2, null); } void Invoke2CallBack(int a) { } }