This code snippet was written to compile the code at run-time. The compiled code works like any other program. Reflection can be accessed with. I want to do a little different things.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
For Example :
My Code is Textbox1.Text="123"; it is in a file or in database.
There is a form.A Textbox in form. I want to use string code as part of my program on runtime.
To do this, you can change the function name to string_Function instead of Main. Save the above code snippet as .cs file. Say Code_Snippet.cs. Now add this file to your MainProject. Wherever you want to use this code snippet you have to write line of code eg Code_Snippet.String_Function(TextBox.Text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.