Compile a C # array at runtime and use it in code?

I know that C # code can be compiled at runtime using C # . However, I am very staggering from this, since I just read about it a few minutes ago. I will learn much better with examples. So tell me. If I want to compile something like:

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

and use this array in my code, how would I do it?

In pseudocode, I want to do something like this:

Open("MapScript.CS");
String[] levelMap = CompileArray("levelMap");
// use the array
+4
source share
3 answers

LINQ Expression trees are probably the friendliest way to do this: Maybe something like:

IL OpCodes (OpCodes.Newarr). , ( ).

, CodeDom ( ), - - . .

MSDN

var ca1 = new CodeArrayCreateExpression("System.Int32", 10);                        
var cv1 = new CodeVariableDeclarationStatement("System.Int32[]", "x", ca1);

- 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() );
+6

, #, (#) .

# . , List<String>. , list.ToArray() .

+2

CompiledLevel, ILevel, Level of type String[].

CompiledLevel.cs , , LevelMap (wwwggg...) ( ).

.

/ factory/ , :)

0
source

All Articles