我尝试编译字符串,但出现错误System.PlatformNotSupportedException: 'Operation is not supported on this platform.'
P.S:
我在以前版本的 .Net Core 中成功运行了此代码,但在 .Net 5 中我遇到了此错误,我发现 .net 5 不再支持从文件和字符串读取和编译
现在我正在寻找一种替代方法来编译我的字符串并在运行时执行我的代码
private void Button_Click(object sender, RoutedEventArgs e)
{
string sourceCode = @"
public class SomeClass {
public int Add42 (int parameter) {
return parameter += 42;
}
}";
var compParms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("SomeClass");
MethodInfo mi = typeInstance.GetType().GetMethod("Add42");
int methodOutput =
(int)mi.Invoke(typeInstance, new object[] { 1 });
textBox.Text = methodOutput.ToString();
}
简短的回答 -CompileAssemblyFromSource
.NET Core 或 .NET 5 不支持。
From 文档 https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider.compileassemblyfromsource?view=windowsdesktop-5.0#exceptions
平台不支持异常
仅限 .NET Core 和 .NET 5+:在所有情况下。
还有其他方法(例如使用Roslyn https://laurentkempe.com/2019/02/18/dynamically-compile-and-run-code-using-dotNET-Core-3.0/)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)