Execute 方法完整代碼
public object Execute(string MethodName, object[] Parameters, bool ThrowException) {
if (CheckReady() == false) return null;
if (ThrowException) {
if (MethodName == null) throw new ArgumentNullException("MethodName");
MethodName = MethodName.Trim();
if (MethodName.Length == 0) throw new ArgumentException("MethodName");
if (myScriptMethods.Count > 0) {
foreach (ScriptMethodInfo info in myScriptMethods) {
if (string.Compare(info.MethodName, MethodName, true) == 0) {
object result = null;
if (info.MethodDelegate != null)
result = info.MethodDelegate.DynamicInvoke(Parameters);
else
result = info.MethodObject.Invoke(null, Parameters);
return result;
}
}
}
} else {
if (MethodName == null) return null;
MethodName = MethodName.Trim();
if (MethodName.Length == 0) return null;
if (myScriptMethods.Count > 0) {
foreach (ScriptMethodInfo info in myScriptMethods) {
if (string.Compare(info.MethodName, MethodName, true) == 0) {
try {
object result = info.MethodObject.Invoke(null, Parameters);
return result;
} catch (Exception ext) {
Console.WriteLine("VBA:" + MethodName + ":" + ext.Message);
}
return null;
}
}
}
}
return null;
}
調用機制關鍵點
- 快取優先:
myScriptMethods 列表快取所有腳本方法資訊,避免每次反射查找
- 雙路徑調用:優先使用
MethodDelegate.DynamicInvoke(效能較佳),退回 MethodInfo.Invoke
- 大小寫不敏感:
string.Compare(..., true) 比對方法名稱
- 參數陣列傳遞:直接轉發
object[] 給目標方法
- 錯誤模式切換:
ThrowException 控制是否向上拋出或靜默記錄
ScriptMethodInfo 結構
private class ScriptMethodInfo {
public string ModuleName;
public string MethodName;
public MethodInfo MethodObject;
public Type ReturnType;
public Delegate MethodDelegate;
}
private ArrayList myScriptMethods = new ArrayList();