首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 發現之旅第十四講:VB.NET 腳本引擎(上)─ Execute 方法完整實作與腳本調用機制

     編輯:關於C語言

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;
}

調用機制關鍵點

  1. 快取優先:myScriptMethods 列表快取所有腳本方法資訊,避免每次反射查找
  2. 雙路徑調用:優先使用 MethodDelegate.DynamicInvoke(效能較佳),退回 MethodInfo.Invoke
  3. 大小寫不敏感:string.Compare(..., true) 比對方法名稱
  4. 參數陣列傳遞:直接轉發 object[] 給目標方法
  5. 錯誤模式切換: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();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved