C# - Load a text file as a class

后端 未结 3 1440
北恋
北恋 2021-01-05 18:34

Is there any way to load a .txt file as a class, which my main program can then call functions from? I\'m basically trying to add mod support to my simple app, where the us

3条回答
  •  失恋的感觉
    2021-01-05 19:09

    See me answer to this question: Compile a C# Array at runtime and use it in code?

    Essentially, you would want to pull your text file into the CodeDom and compile it. After that, it would likely be helpful to create a few dynamic methods as execution helpers.

    • Receive uploaded file
    • Perform any needed validation on the file
    • Read the file as a string into the CodeDom
    • Deal with any compiler/structure errors
    • Create helper methods using Linq expression trees or dynamic methods so that the linkage between the new class and existing code is bridged with a compiled object (otherwise, all the new methods would need to be invoked using reflection)

    var csc = new CSharpCodeProvider( new Dictionary() { { "CompilerVersion", "v4.0" } } );
    var cp = new CompilerParameters() {
        GenerateExecutable = false,
        OutputAssembly = outputAssemblyName,
        GenerateInMemory = true
    };
    
    cp.ReferencedAssemblies.Add( "mscorlib.dll" );
    cp.ReferencedAssemblies.Add( "System.dll" );
    
    StringBuilder sb = new StringBuilder();
    
    // The string can contain any valid c# code
    
    sb.Append( "namespace Foo{" );
    sb.Append( "using System;" );
    sb.Append( "public static class MyClass{");
    sb.Append( "}}" );
    
    // "results" will usually contain very detailed error messages
    var results = csc.CompileAssemblyFromSource( cp, sb.ToString() );
    

    Also, see this topic: Implementing a scripting language in C#. IronPython with the DLR might be suitable for your needs.

提交回复
热议问题