Simulate JavaScript in C # to implement Eval

Source: Internet
Author: User

This problem is encountered in the project, giving a expression, the result is similar to the eval in JavaScript. Colleagues use this method to solve, feel very clever, special affixed to this.

Using the features of the DataTable-compatible SQL formula in Ado.net, it is now concluded that as long as it is a simple formula that can be supported in SQL, the value can be obtained in this way.

Using System;
Using System.Collections;

Public class MyClass
{
    public static void Main ()
    {
  & nbsp;     try
        {
             Double dblresult = convert.todouble (Myclass.eval (@ "1+2*3+120%50/4"));
            Console.Write (Dblresult);
            console.readline ();
       }
        catch (System.Exception ex)
         {
            Console.WriteLine (ex. message);
            console.readline ();
       }
   }

    public static object Eval (string expression)
    {
  
         System.Data.DataTable table=new System.Data.DataTable ();
        System.Data.DataColumn col=new System.Data.DataColumn ("Col1", typeof (String), expression);
        table. Columns.Add (Col);
  
        table. Rows.Add (new object[] {""});
        return table. ROWS[0][0];
   }
}

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.