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

動態執行 C# 代碼互動機制(4):外部變量引用與 ObjectHelper 實作

     編輯:關於C語言

環境變量預處理邏輯

動態代碼中以 `$` 開頭標識外部變量(如 `$argname`),執行前需替換為可存取 Context 字典的包裝物件:

第一階段:處理未初始化變量


// 處理未初始化的環境變量
Regex re = new Regex(@"^(\$)(\w)+");
if (inputCmdString != null)
{
    Match m = re.Match(inputCmdString);
    if (m != null && m.Length > 1)
    {
        String outArgName = inputCmdString.Substring(m.Index, m.Length).Substring(1);
        if (this[outArgName] == null)
        {
            String innerArgName = "TempArg_" + outArgName;
            inputCmdString = "var " + inputCmdString.Replace("$" + outArgName, innerArgName);
            inputCmdString += ";m_context[\"" + outArgName + "\"]=" + innerArgName + ";";
        }
    }
}

第二階段:處理已存在變量


// 處理其它環境變量
re = new Regex(@"(\$)(\w)+");
IDictionary ArgsList = new Dictionary();
if (inputCmdString != null)
{
    MatchCollection mc = re.Matches(inputCmdString);
    if (mc != null)
    {
        foreach (Match m in mc)
        {
            if (m.Length > 1)
            {
                String outArgName = inputCmdString.Substring(m.Index, m.Length).Substring(1);
                if (!ArgsList.ContainsKey(outArgName))
                {
                    Object obj = this[outArgName];
                    if (obj == null) throw new Exception("不存在環境變量 " + outArgName);
                    
                    // 關鍵:使用 ObjectHelper 包裝實現雙向繫結
                    String innerArgName = String.Format(
                        @"(new ObjectHelper<{0}>(m_context,""{1}"")).Obj", 
                        obj.GetType(), outArgName);
                    ArgsList.Add(outArgName, innerArgName);
                }
            }
        }
    }
}

// 批次替換
foreach (String outArg in ArgsList.Keys)
{
    inputCmdString = inputCmdString.Replace("$" + outArg, ArgsList[outArg]);
}

ObjectHelper 泛型包裝類別

解決直接 Cast 無法賦值的問題,實現 Context 字典值的強型別存取與寫回:

public class ObjectHelper
{
    private String m_objName;
    public Context Context { get; private set; }
    
    public T Obj
    {
        get
        {
            Object obj = Context[m_objName];
            return (T)obj;
        }
        set { Context[m_objName] = value; }
    }
    
    public ObjectHelper(Context cxt, String objName)
    {
        m_objName = objName;
        Context = cxt;
    }
}

設計精華

  • 雙向繫結:Property setter 自動寫回 Context,getter 即時讀取
  • 強型別安全:泛型參數 `` 保證編譯期型別檢查
  • 透明代理:動態代碼像操作區域變量一樣操作外部變量
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved