3.0
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
StringBuilder code = new StringBuilder();
code.AppendLine("namespace DotNetCoreTest");
code.AppendLine("{");
code.AppendLine(" public class TestCode");
code.AppendLine(" {");
code.AppendLine(" public int test(int a)");
code.AppendLine(" {");
code.AppendLine(" a++;");
code.AppendLine(" return a;");
code.AppendLine(" }");
code.AppendLine(" }");
code.AppendLine("}");
string sysFile = typeof(Enumerable).Assembly.Location;
string sysDir = Directory.GetParent(sysFile).FullName;
List<MetadataReference> references = new List<MetadataReference>();
references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.dll")));
references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.Xml.dll")));
string assemblyName = "DotNetCoreTest";
SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code.ToString());
CSharpCompilation compilation = CSharpCompilation.Create(assemblyName);
compilation.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
compilation.AddReferences(references);
compilation.AddSyntaxTrees(tree);
string targetPath = "D:\\test.dll";
EmitResult compilationResult = compilation.Emit(targetPath);
string err = "";
if (!compilationResult.Success)
{
foreach (Diagnostic item in compilationResult.Diagnostics)
{
err += "\r\nid: " + item.Id + "\r\nerror: " + item.GetMessage() + "\r\nlocation: " + item.Location.GetLineSpan().ToString();
}
}
id: CS8021错误:没有找到RuntimeMetadataVersion的值。没有找到包含System.Object的程序集,也没有通过选项指定RuntimeMetadataVersion的值。位置:(0,0)-(0,0) id: CS5001错误:程序不包含适合入口点位置的静态“主”方法:(0,0)-(0,0)
我重复了多次测试,并出现了相同的错误消息。我的密码有什么问题吗?有谁可以帮我?谢谢
发布于 2021-01-12 01:24:35
谢谢大家。这个问题已经解决,下一次分享解决方案,但您必须添加依赖“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;
}
}
https://stackoverflow.com/questions/62672954
复制相似问题