[英]Code Compiling on Runtime as part of program
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"; 我的代码是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. 为此,您可以将函数名称更改为string_Function而不是Main。 Save the above code snippet as .cs file.
将上述代码段另存为.cs文件。 Say Code_Snippet.cs.
说出Code_Snippet.cs。 Now add this file to your MainProject.
现在将此文件添加到您的MainProject中。 Wherever you want to use this code snippet you have to write line of code eg Code_Snippet.String_Function(TextBox.Text);
无论您想在何处使用此代码段,都必须编写代码行,例如Code_Snippet.String_Function(TextBox.Text);。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.