本来是想调用复杂js代码的(懒得看懒得重写),结果引用的时候发现要改很多,所以放弃了。这里暂时记录下:
添加引用
c#调用js代码需要添加一个com引用:Microsoft Script Control 1.0
使用
using MSScriptControl;
namespace xxxx.tools
{
class MutateDNA:CodingScheme
{
public MutateDNA() {
base.Init();
shortdesc = "Mutate DNA";
}
public override void Convert()
{
//string path = AppDomain.CurrentDomain.BaseDirectory + @"Resources\scripts\mutate_dna.js";
string path = @"C:\Users\Dell\Desktop\scripts\demo.js";
string str2 = File.ReadAllText(path);
string func = string.Format(@"sayHello('{0}')", source);
string result = ExecuteScript(func, str2);
Console.WriteLine("result: " + result);
//target = result;
}
private string ExecuteScript(string sExpression, string sCode) {
MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
scriptControl.UseSafeSubset = true;
scriptControl.Language = "JScript";
scriptControl.AddCode(sCode);
try
{
string str = scriptControl.Eval(sExpression).ToString();
return str;
}
catch (Exception ex) {
string str = ex.Message;
return str;
}
//return null;
}
}
}
js的内容类似:
function sayHello(str) {
return "Hello, " + str;
}