由于CompileAssemblyFromSource add custom functions in a smart way被忽略,我会以不同的方式提出这个问题,所以人们会费心去阅读它。
在追逐中切割,我正在制作一种语言,通过"翻译"将新语法转换为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);
}
基本上我正在执行一个" main"函数写在code
变量中。
我正在使用代码变量中的一些函数,我希望包括而不是像下面这样在底部添加它作为字符串:
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 main项目中添加一个类,并让编译后的内存代码访问它吗?不将其添加为字符串。
答案 0 :(得分:0)
您可以将源代码文件嵌入为资源。使用此技术,您可以在Visual Studio中编辑该文件,并在运行时访问文件的内容,就好像它是一个字符串一样。
此链接显示了如何执行此操作: https://stackoverflow.com/a/433182/540832