用C#和JS自制脚本语言
用C#和JS自制脚本语言
需要先了解什么?
1、JS Shell Scripting。
2、C#当然是必须的。
利用JS的eval方法建立运行环境
代码如下(示例):
文件名:PEIL.Builder.js
class Env{
function Exec(code){
if(code == ""){
return;
}else{
eval(code);
}
}
}
编译Builder.js
需要把.Net Framework目录添加到Path
用cmd执行命令
jsc /t:library 目录\PEIL.Builder.js
创建C#脚本(用于调用Builder.dll)
文件名:PEIL.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.JScript;
using System.IO;
namespace PEIL{
class Program{
static void Main(string[] args){
Env env = new Env();
Console.Title=">>>PEIL<<<";
if (args.Length == 0){
while (true){
Console.ForegroundColor=ConsoleColor.Blue;
Console.Write("PEIL>>>");
Console.ForegroundColor=ConsoleColor.Green;
String code = Console.ReadLine();
try{
env.Exec(code);
}catch(Exception exception){
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine(exception.Message);
Console.ForegroundColor=ConsoleColor.Green;
}
}
}else{
env.Exec(File.ReadAllText(args[0]));
}
}
}
}
编译PEIL.cs
打开cmd,运行如下命令:
csc /r:"Microsoft.JScript.dll" /r:"System.IO.dll" /r:"刚刚编译的PEIL.Builder.dll" 目录\PEIL.cs
如何自定义函数库
这时,我们需要再新建一个JS脚本
文件名:PEIL.Core.js
import System;
import System.Diagnostics;
import System.Windows.Forms;
package PEIL.Core{
//这是cmd类,包含输入输出函数
class cmd{
function Print(val){
print(val);
}
function ReadLine(){
var val=Console.ReadLine();
return val;
}
function Read(){
var val=Console.Read();
return val;
}
}
//这是system类,提供运行外部程序的函数
class system{
function Run(program,args){
Process.Start(program, args);
}
}
//这是application类,提出结束运行的函数;
class application{
function Exit(){
Environment.Exit(0);
}
}
}
编译:
jsc /t:library 目录\PEIL.Core.js
需要更新PEIL.Builder.js
import PEIL.Core;
\\加了一个import
class Env{
var Cmd=new cmd();//实例化cmd类
var System=new system();//实例化system类
var Application = new application();//实例化application类
function Exec(code){
if(code == ""){
return;
}else{
eval(code);
}
}
}
编译(需要添加引用的库):
jsc /t:library /r:"刚刚编译的PEIL.Core.dll" D:\PEIL\PEIL.Builder.js
测试
新建一个脚本(任意后缀)
Cmd.Print("请输入数字");//这是PEIL.Core.dll提供的函数
var a=Cmd.ReadLine();//这是PEIL.Core.dll提供的函数
if (a==0){ //JS原生支持的if语句
Cmd.Print("Hello");//这是PEIL.Core.dll提供的函数
Application.Exit();//这是PEIL.Core.dll提供的函数
Cmd.Read();//测试 Exit() 是否有效,如果有效,就不会执行这一行
}else{ //JS原生支持的else语句
Cmd.Print("Goodbey");
Cmd.Read();
}
运行cmd命令:
目录\PEIL.exe 刚刚创建的脚本
之后cmd中会出现“请输入数字”
文末
制作不易,多支持小编 😃