【问题标题】:The type or namespace Windows does not exists in namespace System when compiling code dynamically c# [duplicate]c#动态编译代码时,命名空间System中不存在类型或命名空间Windows [重复]
【发布时间】:2017-03-09 14:07:52
【问题描述】:

我需要在我的 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;
                }
            }
        }

但是当我执行它时,我得到了这个错误:

系统命名空间中不存在类型或命名空间 Windows( 缺少程序集参考?)

如果有人知道吗?

提前谢谢你!

【问题讨论】:

  • 你添加了引用吗?
  • @DanielA.White 我在我的项目中得到了参考,我在我的解决方案中使用了 winform
  • 也许这会有所帮助:stackoverflow.com/questions/7605466/…
  • 我觉得System.Windows.Forms.dll应该放在gacc里面,这样可以找到程序集

标签: c# winforms compilation dynamic-compilation


【解决方案1】:

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

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

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

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

【讨论】:

  • 您的解决方案不起作用
  • 我添加了一个有效的修复程序,并对其进行了测试。
  • 天哪!谢谢!
猜你喜欢
  • 2016-10-08
  • 2012-02-22
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
相关资源
最近更新 更多