微软似乎没有明确地提供一个现成的script执行解决方案,我们能想到的就是VSA和CodeDOM。
先看看这个脚本:
1
<dnml>
2
3
<reference assembly="System.Windows.Forms.dll" />
4
5
<language name="C#" entryPoint="Thingy" />
6
7
<waitForUserAction value="true"/>
8
9
<scriptCode><
11
using System;
12
using System.Windows.Forms;
13
14
public class Test
15
{
16
public static int Thingy()
17
{
18
Console.WriteLine("This is a test");
19
Console.WriteLine("This is a another test");
20
Console.WriteLine("Venkat");
21
MessageBox.Show("Neat");
22
23
Test2 two = new Test2();
24
two.Stuff();
25
26
return 5;
27
28
}
29
}
30
31
public class Test2
32
{
33
public void Stuff()
34
{
35
Console.WriteLine("Instance call");
36
}
37
}
38
39
40
]]></scriptCode>
41
42
</dnml>
43
44
<dnml>2

3
<reference assembly="System.Windows.Forms.dll" />4

5
<language name="C#" entryPoint="Thingy" />6

7
<waitForUserAction value="true"/>8

9
<scriptCode><
11
using System;12
using System.Windows.Forms;13

14
public class Test15
{16
public static int Thingy()17
{18
Console.WriteLine("This is a test");19
Console.WriteLine("This is a another test");20
Console.WriteLine("Venkat");21
MessageBox.Show("Neat");22

23
Test2 two = new Test2();24
two.Stuff();25

26
return 5;27

28
}29
}30

31
public class Test232
{33
public void Stuff()34
{35
Console.WriteLine("Instance call");36
}37
}38

39

40
]]></scriptCode>41

42
</dnml>43

44

在CData部分,很熟悉,是吗?对,就是C#。其它部分是:
1、reference:命名空间引用;
2、language:语言;entryPoint是入口;
3、waitForUserAction:等待用户反应(脚本执行完后);
它的原理就是应用CodeDOM在内存中编译和运行这个脚本。
这是原文:Dot Net Script
我修改了一下,将其改变为类库+一个小执行器,更加容易嵌入到你的应用中,这里下载:DotNetScriptEngine.zip。
Dot Net Script的特别之处在于它用了XML来承载脚本,看来起更像脚本。而且代码执行能返回int类型值。
类似的项目还有:NScript - A script host for C#/VB.NET/JScript.NET,不过这个只支持C#,而且不能返回值,但它的架构好很多。