我有控制台应用程序,它应该支持脚本(.cs 文件)以更改应用程序的行为。问题是我有 9 个类型为“未定义或导入预定义类型”的错误
我搜索了很多,无法解决问题,我的代码是
public static void LoadAndRunScript(string fileName, IModbusSlaveNetwork network)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "scripts", fileName);
using (var streamReader = File.OpenRead(path))
{
string generatedAssemblyName = Path.GetRandomFileName();
var refs = new List<MetadataReference>();
foreach (var referencedAssembly in Assembly.GetEntryAssembly().GetReferencedAssemblies())
{
var loadedAssembly = Assembly.Load(referencedAssembly);
refs.Add(MetadataReference.CreateFromFile(loadedAssembly.Location));
}
var compilation = CSharpCompilation.Create(generatedAssemblyName)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(refs)
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(streamReader), path: path));
var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (result.Success)
{
// yay
}
var assembly = LoadAssembly(ms, ms);
assembly.GetType().GetMethod("Start").Invoke(null, new object[] { network });
}
}
private static Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)
{
return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(peStream, pdbStream);
}