【发布时间】:2016-01-12 08:53:45
【问题描述】:
我想从 Codedom 创建的函数返回一个自定义类(例如User)。我的Userclass 与我的Windows Application 在同一解决方案中的另一个类库中,我用它来生成动态代码。
CompilerResult 返回以下错误:
The type or namespace name 'TestApp' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'User' could not be found (are you missing a using directive or an assembly reference?)
这是我的代码:
StringBuilder sbCode = new StringBuilder();
sbCode.Append(@"using System.Windows.Forms;");
sbCode.Append(@"using Nikola.BusinessIntelligence.Objects;");
sbCode.Append(@"using System.Collections.Generic;");
sbCode.Append(@"using System.Text;");
sbCode.Append(@"using Microsoft.CSharp;");
sbCode.Append(@"using TestApp.Data;"); // User class is in this Class Lib
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 User Execute()
{
User usr = new User();
return usr;
}
【问题讨论】:
标签: c# dll .net-assembly codedom