简体   繁体   中英

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. My User class in another class library in the same solution with my Windows Application which I use it for Dynamic Code generation.

CompilerResult returns these errors:

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:

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

Two problems:

  1. You forgot 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; in your code, you must add the something related referenced assembly in the list of referenced assemblies used in 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"
                },

        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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