.net core c#dotNetCore——动态编译代码时出错 .Net核心3.0 Microsoft.CodeAnalysis.CSharp 3.5.0 使用Microsoft.CodeAnalysis; 使用Microsoft.CodeAnalysis.CSharp; 使用Microsoft.CodeAnalysis.Emit; 使用制度; 使用System.Collections.Generic; 使用System.IO; 使用System.Linq; 使用系统文本; StringBuilder代码=新的StringBuilder(); code.AppendLine(“名称空间DotNetCoreTest”); 代码。附录行(“{”); 代码.AppendLine(“公共类测试代码”); 代码。附录行(“{”); 代码.附录行(“公共整数测试(整数a)”); 代码。附录行(“{”); code.AppendLine(“a++;”); code.AppendLine(“返回a;”); 代码。附录行(“}”); 代码。附录行(“}”); 代码。附录行(“}”); 字符串sysFile=typeof(可枚举).Assembly.Location; 字符串sysDir=Directory.GetParent(sysFile).FullName; 列表引用=新列表(); Add(MetadataReference.CreateFromFile(Path.Combine(sysDir,“System.dll”)); Add(MetadataReference.CreateFromFile(Path.Combine(sysDir,“System.Xml.dll”)); 字符串assemblyName=“DotNetCoreTest”; SyntaxTree-tree=SyntaxFactory.ParseSyntaxTree(code.ToString()); csharpcomilation=csharpcomilation.Create(assemblyName); WithOptions(新的CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); 汇编。添加参考文献(参考文献); 汇编.AddSyntaxTrees(tree); 字符串targetPath=“D:\\test.dll”; EmitResult compilationResult=compilation.Emit(targetPath); 字符串err=“”; 如果(!compilationResult.Success) { foreach(compilationResult.Diagnostics中的诊断项) { err+=“\r\nid:”+item.Id+“\r\n错误:“+item.GetMessage()+”\r\n位置:“+item.Location.GetLineSpan().ToString(); } }
id:CS8021 错误:找不到RuntimeMetadataVersion的值。未找到包含System.Object的程序集,也未通过选项指定RuntimeMetadataVersion的值。 位置::(0,0)-(0,0) 身份证号码:CS5001 错误:程序不包含适合入口点的静态“Main”方法 位置::(0,0)-(0,0).net core c#dotNetCore——动态编译代码时出错 .Net核心3.0 Microsoft.CodeAnalysis.CSharp 3.5.0 使用Microsoft.CodeAnalysis; 使用Microsoft.CodeAnalysis.CSharp; 使用Microsoft.CodeAnalysis.Emit; 使用制度; 使用System.Collections.Generic; 使用System.IO; 使用System.Linq; 使用系统文本; StringBuilder代码=新的StringBuilder(); code.AppendLine(“名称空间DotNetCoreTest”); 代码。附录行(“{”); 代码.AppendLine(“公共类测试代码”); 代码。附录行(“{”); 代码.附录行(“公共整数测试(整数a)”); 代码。附录行(“{”); code.AppendLine(“a++;”); code.AppendLine(“返回a;”); 代码。附录行(“}”); 代码。附录行(“}”); 代码。附录行(“}”); 字符串sysFile=typeof(可枚举).Assembly.Location; 字符串sysDir=Directory.GetParent(sysFile).FullName; 列表引用=新列表(); Add(MetadataReference.CreateFromFile(Path.Combine(sysDir,“System.dll”)); Add(MetadataReference.CreateFromFile(Path.Combine(sysDir,“System.Xml.dll”)); 字符串assemblyName=“DotNetCoreTest”; SyntaxTree-tree=SyntaxFactory.ParseSyntaxTree(code.ToString()); csharpcomilation=csharpcomilation.Create(assemblyName); WithOptions(新的CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); 汇编。添加参考文献(参考文献); 汇编.AddSyntaxTrees(tree); 字符串targetPath=“D:\\test.dll”; EmitResult compilationResult=compilation.Emit(targetPath); 字符串err=“”; 如果(!compilationResult.Success) { foreach(compilationResult.Diagnostics中的诊断项) { err+=“\r\nid:”+item.Id+“\r\n错误:“+item.GetMessage()+”\r\n位置:“+item.Location.GetLineSpan().ToString(); } },.net-core,.net Core,id:CS8021 错误:找不到RuntimeMetadataVersion的值。未找到包含System.Object的程序集,也未通过选项指定RuntimeMetadataVersion的值。 位置::(0,0)-(0,0) 身份证号码:CS5001 错误:程序不包含适合入口点的静态“Main”方法 位置::(0,0)-(0,0) 我重复了多次测试,出现了相同的错误消息。我的代码有问题吗?有人能帮我吗?谢谢大家谢谢大家。这个问题已经解决了,接下来分享解决方案, 但您必须添加一个依赖项“Micr
我重复了多次测试,出现了相同的错误消息。我的代码有问题吗?有人能帮我吗?谢谢大家谢谢大家。这个问题已经解决了,接下来分享解决方案, 但您必须添加一个依赖项“Microsoft CodeAnalysis CSharp”
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public class CodeCompiler
{
Assembly TranslateCode(string code, ref string err)
{
Assembly asse = null;
Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
List<MetadataReference> metadataReferences = new List<MetadataReference>();
PortableExecutableReference portable = null;
int len = asses.Length;
int num = 0;
Assembly item = null;
while (num < len)
{
try
{
item = asses[num];
if (string.IsNullOrEmpty(item.Location)) continue;
portable = MetadataReference.CreateFromFile(item.Location);
metadataReferences.Add(portable);
}
catch (Exception)
{
//throw;
}
finally
{
num++;
}
}
var references1 = metadataReferences.ToArray();
string assemblyName = Path.GetRandomFileName();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references1,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
//Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
err += string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage())+"\r\n";
}
}
else
{
// The assembly is loaded from memory when the compilation is successful
ms.Seek(0, SeekOrigin.Begin);
asse = Assembly.Load(ms.ToArray());
}
}
return asse;
}
}
使用Microsoft.CodeAnalysis;
使用Microsoft.CodeAnalysis.CSharp;
使用Microsoft.CodeAnalysis.Emit;
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
运用系统反思;
公共类编解码器
{
程序集转换代码(字符串代码,参考字符串错误)
{
汇编asse=null;
Assembly[]asses=AppDomain.CurrentDomain.GetAssemblys();
List metadataReferences=新列表();
PortableExecutableReference-portable=null;
int len=长度;
int num=0;
组装项=null;
while(num
诊断警告错误||
诊断严重性==诊断严重性错误);
foreach(故障诊断)
{
//WriteLine(“{0}:{1}”,diagnostic.Id,diagnostic.GetMessage());
err+=string.Format(“{0}:{1}”、diagnostic.Id、diagnostic.GetMessage())+“\r\n”;
}
}
其他的
{
//编译成功时,将从内存加载程序集
Seek女士(0,SeekOrigin.Begin);
asse=Assembly.Load(ms.ToArray());
}
}
返回asse;
}
}
我试着在这里用你的代码运行一个测试,我认为除了空的void main之外还有其他一些问题。同样的代码,.net framework下的动态编译完全可以。
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
public class CodeCompiler
{
Assembly TranslateCode(string code, ref string err)
{
Assembly asse = null;
Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
List<MetadataReference> metadataReferences = new List<MetadataReference>();
PortableExecutableReference portable = null;
int len = asses.Length;
int num = 0;
Assembly item = null;
while (num < len)
{
try
{
item = asses[num];
if (string.IsNullOrEmpty(item.Location)) continue;
portable = MetadataReference.CreateFromFile(item.Location);
metadataReferences.Add(portable);
}
catch (Exception)
{
//throw;
}
finally
{
num++;
}
}
var references1 = metadataReferences.ToArray();
string assemblyName = Path.GetRandomFileName();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references1,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
//Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
err += string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage())+"\r\n";
}
}
else
{
// The assembly is loaded from memory when the compilation is successful
ms.Seek(0, SeekOrigin.Begin);
asse = Assembly.Load(ms.ToArray());
}
}
return asse;
}
}