The interface is as follows:
Then, click the UI after the filter button:
Check that the code is filtered out. The Code is as follows (js can call the attributes of the UserInfo class written by C)
Copy codeThe Code is as follows:
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;
}
Let's take a look at the efficiency:
Copy codeThe Code is as follows:
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", useJS_Average );
Msg + = string. Format ("nouseJS_Total: {0} \ r \ n", nouseJS_Total );
Msg + = string. Format ("nouseJS_Average: {0} \ r \ n", nouseJS_Average );
MessageBox. Show (msg );
}
}
Result (the above is the time calculated through the js engine, the following is the pure C # computing time, the tragedy): This Noesis. Javascript is only applicable to scenarios with low performance requirements.