[.NET]使用Script.NET(S#)來做四則運算計算機

[.NET]使用Script.NET(S#)來做四則運算計算機

Script.NET is a dynamic scripting language and runtime infrastructure for making extendable, customizable
and highly flexible applications. It allows introducing macros’ to your applications in the same way as
Microsoft Office deals with VBScript. (from Script.NET language 白皮書)

所以如果要在.NET中動態執行一段Script,就可以使用它來幫忙,例如使用在workflow的判斷式。

今天在論壇上看到「四則運算計算機的相關問題[後序表示法]」,剛好可以用到Script.NET來達到。

在使用它之前,請先到Script.NET version 3 (beta) with .NET 4 support下載對應的版本,筆者是下載「Setup (Pre-release) 01 Nov 2010, v3.0 (x64)」,如下圖,

image

 

安裝完成後,在安裝目錄會有.NET 4, Sliverlight 4的參考組件,及範例等等。

image

 

要做個小小的計算機,我們先建立一個Windows Form專案,然後拉了一個計算機的UI,如下,

image

 

之後只要將USER填入的運算式交給S#運算後,取回結果就可以了,如下的程式,


private void Form1_Load(object sender, EventArgs e)
{
	foreach (Control btn in this.Controls)
	{
		if (btn is Button)
		{
			if (btn.Name.StartsWith("button"))
			{
				btn.Click += Operation_Click;
			}
		}
	}
}

//串接運算式
private void Operation_Click(object sender, EventArgs e)
{
	Button operBtn = (sender as Button);
	if(operBtn != null)
		txtResult.Text += (sender as Button).Text;
}

private void btnExec_Click(object sender, EventArgs e)
{
	RuntimeHost.Initialize();
	const string calculatorOpeations = "return {0};";
	string operations = String.Format(calculatorOpeations, txtResult.Text);  
	Script s = Script.Compile(operations);
	string result = s.Execute().ToString();
	RuntimeHost.CleanUp();
	lblResult.Text = txtResult.Text + " = " + result;
	txtResult.Text = result;
}

private void btnClear_Click(object sender, EventArgs e)
{
	txtResult.Text = string.Empty;
}

image

image

簡單的計算機就完成了!

 

範例程式

 

參考資料

Script.NET a language for embedding scripting functionality into CLR Applications

.NET 动态脚本语言Script.NET 入门指南 Quick Start

S#

Microsoft  “Roslyn” CTP

在.NET中使用Javascript作为脚本语言(v8最新版)

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^