MethodExpression
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Pattern.Interpreter
{
/**//// <summary>
/// 終端公式(TerminalExpression)分析與方法相關的
/// </summary>
public class MethodExpression : AbstractExpression
{
/**//// <summary>
/// 從輸入內容中取得要解釋的詞
/// </summary>
/// <param name="source">source</param>
/// <returns></returns>
public override string GetWord(string source)
{
MatchCollection mc;
Regex r = new Regex(@"\((.*)\)");
mc = r.Matches(source);
return mc[0].Groups[1].Value;
}
/**//// <summary>
/// 獲取與方法相關的字典
/// </summary>
/// <returns></returns>
public override Dictionary<string, string> GetDictionary()
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("獲取", ".Get()");
return d;
}
}
}
clIEnt
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.CSharp;
using System.Reflection;
using System.Text;
using System.Collections.Generic;
using Pattern.Interpreter;
public partial class Interpreter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string chinese = "{數據庫}[信息](獲取)";
Context context = new Context(chinese);
List<AbstractExpression> l = new List<AbstractExpression>();
l.Add(new DatabaseExpression());
l.Add(new ObjectExpression());
l.Add(new MethodExpression());
foreach (AbstractExpression exp in l)
{
exp.Interpret(context);
}
Assembly assembly = Assembly.Load("Pattern.Interpreter");
MethodInfo method = assembly.GetType("Pattern.Interpreter." + context.Output.Split('.')[0]).GetMethod(context.Output.Split('.')[1].Replace("()", ""));
object obj = method.Invoke(null, null);
List<MessageModel> m = (List<MessageModel>)obj;
Response.Write("中文語法:" + chinese);
Response.Write("<br />");
Response.Write("解釋後的C#代碼:" + context.Output);
Response.Write("<br />");
Response.Write("執行結果:" + m[0].Message + " " + m[0].PublishTime.ToString());
}
}
運行結果
中文語法:{數據庫}[信息](獲取)
解釋後的C#代碼:SqlMessage.Get()
執行結果:SQL方式獲取Message 2007-5-1 8:48:07
參考
http://www.dofactory.com/Patterns/PatternInterpreter.ASPx
OK