2012-07-31 93 views
4

I know C# code can be compiled at runtime using C#。但是我几分钟前刚刚读过它,所以我非常不高兴。我通过例子学到了很多东西。所以告诉我。如果我想编译类似:在运行时编译C#数组并在代码中使用它?

// MapScript.CS 
String[] LevelMap = { 
"WWWWWWWWWWWWWWWWWWW", 
"WGGGGGGGGGGGGGGGGGW", 
"WGGGGGGGGGGGGGGGGGW", 
"WWWWWWWWWWWWWWWWWWW" }; 

,并在我的代码中使用此阵,我会怎么做呢?

在伪我希望做这样的事情:

Open("MapScript.CS"); 
String[] levelMap = CompileArray("levelMap"); 
// use the array 
+2

你希望通过编译这个字符串数组来实现什么?它将被编译成什么? – dthorpe 2012-07-31 20:58:52

+0

我真的不确定你的问题是关于什么的。是关于在运行时创建字符串数组吗?如何从文本文件加载字符串? – 2012-07-31 21:00:12

+0

在运行时将它读入已经编译好的数组中可能会复杂得多也很痛苦。 – Wug 2012-07-31 21:00:18

回答

6

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()); 
0

您可以创建一个类CompiledLevel继承ILevel它提出了一个静态属性String[]水平

然后,在编译之前,创建一个假CompiledLevel.cs文件从类的充满了LevelMap内容(wwwggg ......)的模板(排序级联)建成。

编译后的一个,调用级别编译后的类的属性。

创建服务/工厂/不管使它看上:)

2

看来,你是想编写C#代码以加载文本(C#)字符串列表文件转换成字符串数组变量。

您不需要c#编译器将文本文件中的字符串列表加载到内存中的数组中。只需在文本文件中每行放置一个字符串,并在代码中逐行读取文件,将每行添加到List<String>。当你完成后,list.ToArray()将产生你的字符串数组。

相关问题