您好,登录后才能下订单哦!
本篇内容介绍了“如何利用noesis.Javascript开源组件.Net中执行javascript脚本”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
界面如下:
然后,click filter button后的UI:
看,筛选出来了,代码如下(js能调C#写的UserInfo类的各个属性)
复制代码 代码如下:
public class UserInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("{0}, {1}: {2}", FirstName, LastName, Age);
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
List<UserInfo> users = FilterUsers(txtFilter.Text.Trim());
lstUsers.DataSource = users;
}
private List<UserInfo> FilterUsers(string jsFilter)
{
List<UserInfo> results = new List<UserInfo>();
if (jsFilter.Trim().Length == 0)
return this.users;
try
{
using (JavascriptContext context = new JavascriptContext())
{
foreach (UserInfo user in this.users)
{
context.SetParameter("user", user);
context.SetParameter("isInclude", false);
string js = string.Format(@"
if({0})
isInclude=true;
else
isInclude=false;", jsFilter);
context.Run(js);
bool isInclude = (bool)context.GetParameter("isInclude");
if (isInclude)
results.Add(user);
}
}
}
catch
{
txtFilter.Focus();
txtFilter.SelectAll();
return this.users;
}
return results;
}
我们来看看效率:
复制代码 代码如下:
private void btnTest_Click(object sender, EventArgs e)
{
using (JavascriptContext context = new JavascriptContext())
{
Stopwatch sw = new Stopwatch();
sw.Start();
int i=1000000;
while(i-- > 0)
{
context.SetParameter("ii", 1);
context.SetParameter("jj", 2);
context.SetParameter("sum", 0);
string js = string.Format(@"sum=ii+jj;");
context.Run(js);
int sum = (int)context.GetParameter("sum");
}
sw.Stop();
long useJS_Total = sw.ElapsedMilliseconds;
float useJS_Average = ((float)sw.ElapsedMilliseconds) / 1000000;
sw.Reset();
sw.Start();
i = 1000000;
while (i-- > 0)
{
int ii = 1;
int jj = 2;
int sum = 0;
sum = ii + jj;
}
sw.Stop();
long nouseJS_Total = sw.ElapsedMilliseconds;
float nouseJS_Average = ((float)sw.ElapsedMilliseconds) / 1000000;
string msg = "";
msg += string.Format("useJS_Total: {0}\r\n", useJS_Total);
msg += string.Format("useJS_Average: {0}\r\n\r\n\r\n", useJS_Average);
msg += string.Format("nouseJS_Total: {0}\r\n", nouseJS_Total);
msg += string.Format("nouseJS_Average: {0}\r\n\r\n\r\n", nouseJS_Average);
MessageBox.Show(msg);
}
}
结果(上面的是通过js引擎计算的时间、下面的是纯C#计算时间,悲剧啊):这个Noesis.Javascript只适用于性能要求不高的场合
“如何利用noesis.Javascript开源组件.Net中执行javascript脚本”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。