【问题标题】:How to impelement referenced assemblies to codedom in C#如何在 C# 中将引用的程序集实现到 codedom
【发布时间】:2016-01-12 07:49:54
【问题描述】:

我想使用 CodeDom 技术。但是,我找不到将引用的程序集引入我的动态代码的正确方法。如果我只写简单的声明代码(例如return "test"),一切都很好。但是当我想使用 MessabeBox 编译结果错误包含The name 'MessageBox' does not exist in the current context

 StringBuilder sbCode = new StringBuilder();

 sbCode.Append("public class Test {");
 sbCode.Append(tbCode.Text);
 sbCode.Append("}");
var cp = new CompilerParameters()
{
   GenerateInMemory = true,
   GenerateExecutable = false,
   ReferencedAssemblies =
    {
     "System.dll",
      "System.Core.dll",
      "System.Windows.dll",
      "System.Windows.Forms.dll"
    }
  };

  using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
   {
     CompilerResults res = codeProvider.CompileAssemblyFromSource(cp, sbCode.ToString());
     var type = res.CompiledAssembly.GetType("Test"); 
     var obj = Activator.CreateInstance(type);
     var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
   }

这是我在 tbCode 文本框中编写的示例代码:

public string Execute()
{
 MessageBox.Show("adsf");
return "asdf";
}

【问题讨论】:

  • 引用只是链接 dll。您是否尝试添加 using 语句?

标签: c# dll .net-assembly dllimport codedom


【解决方案1】:

您应该在类声明的开头添加所需的“使用”语句:

using System.Windows.Forms;

您也可以使用完整的命名空间调用 MessageBox:

public string Execute()
{
 System.Windows.Forms.MessageBox.Show("adsf");
return "asdf";
}

【讨论】:

  • 非常感谢。如果我想使用自定义对象作为返回类型?例如,我的解决方案中有类库,我想使用代码圆顶返回一个类。我尝试像系统一样给库命名空间,但它不起作用。
猜你喜欢
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
相关资源
最近更新 更多