使用需求
有时候一段Javascript代码写的很棒,而我们又无法将之翻译成.net或翻译之成本很高的时候
我们就可以使用Jint引擎来运行Javascript代码,来得到我们想要的结果
或者上
http://jint.codeplex.com/releases/view/119215
下面代码使用的 0.9.2.0 版本
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Jint; namespace JIntTest { /// <summary> /// 这里一这要是 public,否则JInt无法反射 /// </summary> public class Student { public string Id { get; set; } public string Name { get; set; } } class Program { static void Main(string[] args) { //简单判断 var b = JavascriptUtil.Execute<int>("1>0", null); //直接给参数赋值
string str = "var stu={};stu.Id=Id;stu.Name=Name; return stu.Id"; Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("Id", "001"); dict.Add("Name", "Aven"); var c = JavascriptUtil.Execute<string>(str, dict); //通过类实例来赋值 Dictionary<string, object> dict2 = new Dictionary<string, object>(); var st = new Student//这里一定要使用public { Id = "002", Name = "Grace" }; dict2.Add("ST",st); var str2 = "var stu={};stu.Id=ST.Id;stu.Name=ST.Name; return stu.Id"; var d = JavascriptUtil.Execute<string>(str2, dict2); } public static string ReadFile(string path) { StreamReader sr = new StreamReader(path, Encoding.Default); String line; StringBuilder sb = new StringBuilder(); while ((line = sr.ReadLine()) != null) { sb.AppendLine(line); } return sb.ToString(); } } public static class JavascriptUtil { static JavascriptUtil() { } public static object Execute<T>(string expression, Dictionary<string, object> args) { if (string.IsNullOrEmpty(expression)) { if (typeof(T) == typeof(int) || typeof(T) == typeof(decimal) || typeof(T) == typeof(double) || typeof(T) == typeof(float)) { return 0; } if (typeof(T) == typeof(DateTime)) { return DateTime.MinValue; } if (typeof(T) == typeof(string)) { return ""; } return default(T); } if(typeof(T)==typeof(int)) { var result = JintExecute(expression, args); return Convert.ToInt32(result); } if (typeof(T) == typeof(decimal )) { var result = JintExecute(expression, args); return Convert.ToDecimal(result); } if (typeof(T) == typeof(double )) { var result = JintExecute(expression, args); return Convert.ToDouble(result); } if (typeof(T) == typeof(DateTime )) { var result = JintExecute(expression, args); return Convert.ToDateTime(result); } return JintExecute(expression, args); } public static object JintExecute(string expression, Dictionary<string, object> args) { var engine = _engine; if (args != null) { foreach (var x in args) { engine.SetParameter(x.Key, x.Value); } } return engine.Run(expression) ; } private static JintEngine _engine= new JintEngine(); } }
时间: 2024-10-13 10:54:18