In C #, convert the string to the calculation formula and calculate the result,
According to the summary, there are three types:
First, use the Compute method in the DataTable.
Example: "1*2*3"
The Code is as follows:
Var a = new System. Data. able (). Compute ("1*2*3", ""); // result a => 6
Method 2: parse using Eval method in javascript. This method requires adding COM reference: Microsoft Sctipt Control 1.0
During use, if the interoperability type "MSScriptControl. ScriptControlClass" cannot be embedded, you can perform this operation. Right-click MSScriptControl assembly --> Property --> embedded interoperability type --> change to false
Let's take a look at the power of this method:
Example: "1*2*3"
This method can also parse strings like this: "if (3> 2) {1} else {2 }"
The Code is as follows:
MSScriptControl. scriptControl SC = new MSScriptControl. scriptControlClass (); SC. language = "javascript"; var B = SC. eval ("1*2*3"); // Result B => 6
Third: Introduce and Add. net references Microsoft. JScript and Microsoft. Vsa
I personally think this method is the same as method 2, but the specific difference is unclear.
Example: "1*2*3"
This method can also parse strings like this: "if (3> 2) {1} else {2}", the same as method 2.
The Code is as follows:
Microsoft. JScript. vsa. vsaEngine ve = Microsoft. JScript. vsa. vsaEngine. createEngine (); var c = Microsoft. JScript. eval. JScriptEvaluate ("1*2*3", ve); // Result c => 6
In summary, similar cases may inevitably occur in projects. I personally think that if it is only a simple calculation, the first one is undoubtedly the most convenient. If there is a logical string to be parsed, the second or third type is used.
I personally like it.
This article ends here. Thank you for watching.