Delegate實現動態執行方法
通過 Delegate.CreateDelegate方法實現動態執行指定方法
聲明委託:
public delegate void DelegateMethod();
實例化方法調用
ClassName classInstance = new ClassName();
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
MethodInfo minfo = typeof(ClassName).GetMethod("MethodName", flags);
DelegateMethod dm = (DelegateMethod)Delegate.CreateDelegate(typeof(DelegateMethod), classInstance, minfo, false);
dm();
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
MethodInfo minfo = typeof(ClassName).GetMethod("MethodName", flags);
DelegateMethod dm = (DelegateMethod)Delegate.CreateDelegate(typeof(DelegateMethod), classInstance, minfo, false);
dm();
靜態方法調用
BindingFlags flags = BindingFlags.Public | BindingFlags.Static;
MethodInfo minfo = typeof(ClassName).GetMethod("MethodName", flags);
DelegateMethod dm = (DelegateMethod)Delegate.CreateDelegate(typeof(DelegateMethod), minfo);
dm();
MethodInfo minfo = typeof(ClassName).GetMethod("MethodName", flags);
DelegateMethod dm = (DelegateMethod)Delegate.CreateDelegate(typeof(DelegateMethod), minfo);
dm();
方法名稱通過 ”MethodName" 動態傳入
實例方法和動態方法的區別在於 BindingFlags和CreateDelegate方法。