将类添加到已编译的程序集(内存中)

本文关键字:程序集 内存 编译 添加 | 更新日期: 2023-09-27 18:25:35

由于CompileAssemblyFromSource以智能方式添加自定义函数被忽略,我将以不同的方式问这个问题,所以人们会麻烦阅读它。

切入正题,我正在通过将新语法"翻译"成c#并以这种方式在内存中编译来制作一种语言。

using (Microsoft.CSharp.CSharpCodeProvider CodeProv =
    new Microsoft.CSharp.CSharpCodeProvider())
    {
        CompilerResults results = CodeProv.CompileAssemblyFromSource(
             new System.CodeDom.Compiler.CompilerParameters()
             {
                 GenerateInMemory = true
             },
             code);
         var type = results.CompiledAssembly.GetType("MainClass");
         var obj = Activator.CreateInstance(type);
         var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
         Console.WriteLine(output);
    }

基本上,我正在执行一个写在code变量内部的"main"函数。我在代码变量中使用了一些函数,我想在不将其添加为底部的字符串的情况下包括这些函数:

        code += @"public void Write(string path, object thevar)
        {
        if (thevar.GetType() == typeof(string))
        {
        System.IO.File.WriteAllText(path,(string)thevar);
        }
        if (thevar.GetType() == typeof(string[]))
        {
        System.IO.File.WriteAllLines(path,(string[])thevar);
        }
        }";

我可以从VS中的Actual主项目中添加一个类,并让编译后的内存代码访问它吗?而不将其作为字符串添加。

将类添加到已编译的程序集(内存中)

您可以将源代码文件作为资源嵌入。使用此技术,您可以在VisualStudio中编辑文件,并在运行时访问文件的内容,就好像它是一个字符串一样。

此链接显示如何执行:https://stackoverflow.com/a/433182/540832