在C#中,委托的動態綁定可以通過以下幾種技巧實現:
Action<int> action = x => Console.WriteLine(x);
action(10); // 輸出: 10
Func<int, int> myFunc = x => x * 2;
int result = myFunc(5); // 返回 10
Action<int> action1 = x => Console.WriteLine(x);
Action<int> action2 = x => Console.WriteLine(x * 2);
Action<int> combinedAction = null;
combinedAction = (Action<int>)Delegate.Combine(combinedAction, action1);
combinedAction = (Action<int>)Delegate.Combine(combinedAction, action2);
combinedAction(5); // 輸出: 5 10
MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
Action<int> myAction = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), null, methodInfo);
myAction(10);
這些技巧可以幫助在C#中實現委托的動態綁定,從而實現更加靈活和動態的方法調用。