简体   繁体   English

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

[英]Add class to compiled assembly (in memory)

Since CompileAssemblyFromSource add custom functions in a smart way was ignored im going to ask this question differently so people will bother to read it. 由于CompileAssemblyFromSource以智能方式添加自定义函数被忽略,我会以不同的方式提出这个问题,所以人们会费心去阅读它。

cutting at the chase,i am making a language by "translating" the new syntax into c# and compiling it in memory in this fashion. 在追逐中,我通过将新语法“翻译”成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);
    }

basically i am executing a "main" function written inside the code variable. 基本上我正在执行一个写在code变量中的“main”函数。 and i am using some functions in the code variable i would like to include without adding it as a string at the bottom like this: 我正在使用代码变量中的一些函数我想包括而不是像底部一样添加它作为一个字符串,如下所示:

        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);
        }
        }";

Can i somehow add a class from my Actual main project in VS and let the compiled in memory code access it? 我可以以某种方式从VS中的Actual main项目中添加一个类,并让编译后的内存代码访问它吗? without adding it as a string. 不添加它作为字符串。

You can embed your source code file(s) as resources. 您可以将源代码文件嵌入为资源。 With this technique you can edit the file in Visual Studio and access the contents of the files as if it was a string during run-time. 使用此技术,您可以在Visual Studio中编辑该文件,并在运行时访问文件的内容,就好像它是一个字符串一样。

This link shows how to do it: https://stackoverflow.com/a/433182/540832 此链接显示了如何执行此操作: https//stackoverflow.com/a/433182/540832

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM