LINQ表达式树可能是这样做的友好的方式:也许是这样的:
您也可以生成IL使用OpCodes(OpCodes.Newarr)。如果您对基于堆栈的编程感到满意,则很容易(否则,可能会很有挑战性)。最后,你可以使用CodeDom(你的伪代码类似),但是 - 虽然是最强大的工具,但它不太适合快速动态方法。由于您正在与编译器密切合作,因此它需要文件系统权限和手动引用解析。从MSDN
var ca1 = new CodeArrayCreateExpression("System.Int32", 10);
var cv1 = new CodeVariableDeclarationStatement("System.Int32[]", "x", ca1);
Source - Creating Arrays with the Code DOM
如果你想要一个字符串的直线上升生编译,则可以省略报表的面向对象的处理,而不是只建立一个大的字符串
样品。喜欢的东西:
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
var cp = new CompilerParameters() {
GenerateExecutable = false,
OutputAssembly = outputAssemblyName,
GenerateInMemory = true
};
cp.ReferencedAssemblies.Add("mscorlib.dll");
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("System.Core.dll");
StringBuilder sb = new StringBuilder();
// The string can contain any valid c# code, but remember to resolve your references
sb.Append("namespace Foo{");
sb.Append("using System;");
sb.Append("public static class MyClass{");
// your specific scenario
sb.Append(@"public static readonly string[] LevelMap = {
""WWWWWWWWWWWWWWWWWWW"",
""WGGGGGGGGGGGGGGGGGW"",
""WGGGGGGGGGGGGGGGGGW"",
""WWWWWWWWWWWWWWWWWWW"" };");
sb.Append("}}");
// "results" will usually contain very detailed error messages
var results = csc.CompileAssemblyFromSource(cp, sb.ToString());
你希望通过编译这个字符串数组来实现什么?它将被编译成什么? – dthorpe 2012-07-31 20:58:52
我真的不确定你的问题是关于什么的。是关于在运行时创建字符串数组吗?如何从文本文件加载字符串? – 2012-07-31 21:00:12
在运行时将它读入已经编译好的数组中可能会复杂得多也很痛苦。 – Wug 2012-07-31 21:00:18