动态编译代码时,命名空间系统中不存在类型或命名空间Windows c#

The type or namespace Windows does not exists in namespace System when compiling code dynamically c#

我需要在我的 Winform 应用程序中动态编译一些代码来执行用户编写的 C# 代码。

为了做一些测试,我写了这个函数:

public object executeDynamicCode(string code)
        {
            using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider())
            {
                try
                {
                    var res = foo.CompileAssemblyFromSource(
                        new System.CodeDom.Compiler.CompilerParameters()
                        {
                            GenerateInMemory = true
                        },
                        "using System.Windows.Forms; public class FooClass { public void Execute() {MessageBox.Show();}}");
                    if (res.Errors.Count > 0)
                        MessageBox.Show(res.Errors[0].ErrorText);
                    var type = res.CompiledAssembly.GetType("FooClass");
                    var obj = Activator.CreateInstance(type);
                    var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
                    return output;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    return null;
                }
            }
        }

但是当我执行它时,出现了这个错误:

The type or namespace Windows does not exists in System namespace (an assembly reference are missing ?)

如果有人有任何想法?

提前致谢!

向其中添加一个命名空间,与您的主项目的命名空间相匹配。我相信它是在单独的上下文中执行的,因为它没有相同的命名空间,所以它找不到项目其余部分中包含的引用。

此外,将编译器选项更改为

                    new System.CodeDom.Compiler.CompilerParameters()
                    {
                        GenerateInMemory = true,
                        CoreAssemblyFileName = "mscorlib.dll",
                        ReferencedAssemblies = { "System.dll", "System.Windows.dll", "System.Windows.Forms.dll","Microsoft.CSharp.dll" }
                    }

有效,我试过了。您可能不需要所有这些引用的程序集,真正重要的是 CoreAssemblyFileName。