In C #, convert the string to the calculation formula and calculate the result,

Source: Internet
Author: User

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.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.