【发布时间】: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
-
我觉得
System.Windows.Forms.dll应该放在gacc里面,这样可以找到程序集
标签: c# winforms compilation dynamic-compilation