[英]C# CompileAssemblyFromSource, add referenced assemblies it needs?
[英]How to impelement referenced assemblies to codedom in C#
我想使用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";
}
您應該在類聲明的開頭添加所需的“ using”語句:
using System.Windows.Forms;
您還可以使用完整的命名空間調用MessageBox:
public string Execute()
{
System.Windows.Forms.MessageBox.Show("adsf");
return "asdf";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.