js| string today in the forum to find a problem is more typical, we use JS can directly use the eval to get an expression of the value, in C # can it? The answer is yes, it is achievable in the rich class libraries provided by. NET, but without JS, I'll use a simple example to illustrate the value of a string expression using the compiler and reflection. We create a Windows Form that has the following methods:
Reference namespaces:
Using System;
Using System.Text;
Using System.CodeDom.Compiler;
Using System.Reflection;
Using System.IO;
Using Microsoft.csharp;
The specific meaning of the namespace does not say, the following look at the code, in order to let our project can be reused we create a new class Library project name: Coustomeval One of the classes is the value used to compute a broken string. The detailed code looks like this:
Namespace coustomeval{
///
Summary description for Class1.
///
public class myeval{
Public Myeval () {
//
Todo:add constructor Logic here
//
}
public Object Eval (string ccharpcode) {
CSharpCodeProvider CSharpCodeProvider = new CSharpCodeProvider ();
The above class library only has the general representative does not have the general usability, the important is provides a method to implement it, therefore I use in the inside the hard coding way, if you like can use other way, including reads the file, reads the database to obtain the code paragraph and so on. And then we're building a test project that has a test form with a button and two text boxes, one text box to enter the value to calculate, and the other to display the results of the calculation, detailed code as follows:
In this project, we need to refer to the above project, so that we can use the Myeval class to achieve the calculation of the value of the TextBox1, and finally can display the value in the TextBox2, the results of the operation of the code here I do not post. Only give my test results, because the problem originated from the forum so I am using the original test requirements in the forum.
Test Result: Enter int i = 10 in textbox, and click Button1 will show 10 in TextBox2.
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.