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

C# 动态编译c代码时,命名空间系统中不存在类型或命名空间窗口#,c#,winforms,compilation,dynamic-compilation,C#,Winforms,Compilation,Dynamic Compilation,我需要在Winform应用程序中动态编译一些代码,以执行用户编写的C#代码 为了进行一些测试,我编写了以下函数: public object executeDynamicCode(string code) { using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider()) { try

我需要在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;
                }
            }
        }
但是当我执行它时,我得到了这个错误:

系统命名空间中不存在类型或命名空间窗口(一个 缺少程序集引用吗?)

有人知道吗


提前谢谢你

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

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

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

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

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

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

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

行得通,我试过了。您可能不需要所有引用的程序集,真正重要的是CoreSassemblyFileName。

您添加了引用吗?@DanielA.White我在项目中获得了引用,我在我的解决方案中使用winform可能会有所帮助:我认为
System.Windows.Forms.dll
应该放在gacc中,以便可以找到程序集。您添加了引用吗?@DanielA.White我在我的项目中获得了引用,我在我的解决方案中使用winform也许这会有所帮助:我认为
System.Windows.Forms.dll
应该放在gacc中,这样就可以找到程序集。你的解决方案不起作用了。我添加了一个有效的修复程序,并对其进行了测试。哦,上帝!谢谢你的解决方案不起作用我添加了一个有效的修复程序,并对其进行了测试。哦,天哪!谢谢