將inputCmdString中的外部變量$argname統一替換為(new ObjectHelper <m_context[“argname” ].GetType()> (m_context, “argname”)).Obj" 即可實現在動態代碼中對已定義外部變量的引用。
上述對inputCmdString的預處理代碼為:
Regex re;
// 處理未初始化的環境變量 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<String, String> ArgsList = new Dictionary<String, String>(); 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); 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]); } }