利用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只适用于性能要求不高的场合
上一篇: NET索引器使用方法实例代码