此代码片段是为了在运行时编译代码而编写的。 编译后的代码与任何其他程序一样。 反射可以通过访问。 我想做一点不同的事情。代码在运行时作为程序的一部分编译
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));
}
}
例如:
我的代码是Textbox1.Text = “123”;它位于文件或数据库中。
有一个form.A形式的文本框。 我想在运行时使用字符串代码作为我的程序的一部分。
你能解释一下你想做什么吗?目前还不清楚代码段与你的问题有什么关系。 – 2013-03-18 05:23:56
也许他想写的东西是:'var Textbox1 = ..;执行( “Textbox1.Text = '123'”); '。即他想使用运行代码的上下文来执行一些代码。 – VorobeY1326 2013-03-18 05:32:21
你所有的代码就像'textbox.Text =“...”'?也许你会发现,如果你只是在某个文件中存储了一组键/值对(即“Textbox1.Text”,“123”),它会更容易。这听起来像你试图实现[应用程序本地化](http://msdn.microsoft.com/en-us/library/5839we2z.aspx)...也许你应该看看[resx](http:///msdn.microsoft.com/en-us/library/ekyft91f%28v=vs.90%29.aspx)文件。 – 2013-03-18 05:43:08