简体   繁体   English

如何从C#中的CodeDom返回自定义类?

[英]How to return a custom class from CodeDom in C#?

I want to return a custom class (ex. User ) from a function which created by a Codedom. 我想从Codedom创建的函数中返回自定义类(例如User )。 My User class in another class library in the same solution with my Windows Application which I use it for Dynamic Code generation. 我的User类与Windows Application在同一解决方案中的另一个类库中,该类用于动态代码生成。

CompilerResult returns these errors: 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?)

Here is my code : 这是我的代码:

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[] { });
}

And here is my sample code which I write in tbCode text box: 这是我在tbCode文本框中编写的示例代码:

public User  Execute()
        {
            User usr = new User();
            return usr;
        }

Two problems: 两个问题:

  1. You forgot namespace : 您忘记了namespace

     sbCode.Append(" namespace SomeNameSpace{public class Test {"); sbCode.Append(tbCode.Text); sbCode.Append("}}"); 
  2. There is missing = in code you are trying: 您尝试的代码中缺少=

     User usr = new User(); 

In regards of compiler errors, you have to add missing assemblies. 关于编译器错误,您必须添加缺少的程序集。 Try to add all used by current assembly like this: 尝试像这样添加当前程序集使用的所有内容:

var options = new CompilerParameters();
// add all loaded assemblies
options.ReferencedAssemblies.AddRange(
    AppDomain.CurrentDomain.GetAssemblies().Where(item => !item.IsDynamic).Select(item => item.Location).ToArray());
options.GenerateExecutable = false;
options.GenerateInMemory = true;

// compile like this
var result = provider.CompileAssemblyFromSource(options, source);
if (result.Errors.HasErrors)
{
    // deal with errors
}

Obviously if you type a using something; 显然,如果您using something;输入a using something; in your code, you must add the something related referenced assembly in the list of referenced assemblies used in CompilerParameters : 在你的代码,你必须添加something在使用引用的程序列表中的相关引用的程序集CompilerParameters

var cp = new CompilerParameters()
        {
            GenerateInMemory = true,
            GenerateExecutable = false,
            ReferencedAssemblies =
            {
                "System.dll",
                "System.Core.dll",
                "System.Windows.dll",
                "System.Windows.Forms.dll",
                // I assume the following name of the assembly
                // however you should update it to the relevant name if needed
                "TestApp.Data.dll"
                },

        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM