C# 版本的 Eval
Eval 的功用就是把運算式字串,把運算式的結果回傳。例如:"3 +5" 的運算式字串,Eval 回傳 8。"3 < 5" 的運算式字串,Eval 回傳 True。以下範例使用 CodeDom 方式來解議,該效能不是很好,請不要隨便亂用。
EvaluatorTest.aspx
1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="EvaluatorTest.aspx.cs" Inherits="EvaluatorTest" %>
2:
3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4: <html xmlns="http://www.w3.org/1999/xhtml">
5: <head runat="server">
6: <title>Evaluator Test</title>
7: </head>
8: <body>
9: <form id="form1" runat="server">
10: <div>
11: 運算式:<asp:TextBox ID="txtStatement" runat="server" Text="3 + 3 > 5"></asp:TextBox>
12: <asp:Button ID="btnEval" runat="server" Text="Eval" OnClick="btnEval_Click" />
13: <br />
14: ( 請輸入運算式,例如: 3 + 2、3 - 2、3 + 2 == 5 或 3 > 2 等。)
15: <br />
16: <br />
17: 結果:<asp:Label ID="lbResult" runat="server" ForeColor="Red" Font-Bold="true"></asp:Label>
18: </div>
19: </form>
20: </body>
21: </html>
EvaluatorTest.aspx.cs
1: using System;
2: using System.CodeDom.Compiler;
3: using System.Reflection;
4:
5: public partial class EvaluatorTest: System.Web.UI.Page
6: {
7: protected void btnEval_Click(object sender, EventArgs e)
8: {
9: lbResult.Text = Evaluator.Eval(txtStatement.Text.Trim()).ToString();
10: }
11: }
12:
13: public class Evaluator
14: {
15: public static object Eval(string statement)
16: {
17: return _evaluatorType.InvokeMember("Eval", BindingFlags.InvokeMethod, null, _evaluator, new object[] {statement});
18: }
19:
20: static Evaluator()
21: {
22: CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript");
23: CompilerParameters parameters;
24: parameters = new CompilerParameters();
25: parameters.GenerateInMemory = true;
26:
27: CompilerResults results;
28: results = provider.CompileAssemblyFromSource(parameters, _jscriptSource);
29:
30: Assembly assembly = results.CompiledAssembly;
31: _evaluatorType = assembly.GetType("Evaluator");
32: _evaluator = Activator.CreateInstance(_evaluatorType);
33: }
34:
35: private static readonly object _evaluator;
36: private static readonly Type _evaluatorType;
37: private static readonly string _jscriptSource = @"class Evaluator { public function Eval(expr : String) : String { return eval(expr); } }";
38: }