Question

I have spent some time trying to building an entity graph dynamically with Reflection.Emit. Creating a assembly with a new flat type (class), instantiate it and use it with reflection is easy and works fine. But when it comes to building a structure with generic lists of yet another dynamic classes, it gets more complicated and I got stuck. Basically, I would like to build the following structure dynamically:

public class Head
{
    public string HeadId { get; set; }
    public AssignmentType HeadType { get; set; }
    public int TestIndicator { get; set; }
    public List<Item> Items { get; set; }

    public Head()
    {
        Items = new List<Item>();
    }
}

public class Item
{
    public string ItemId { get; set; }
    public int Weight { get; set; }
    public List<Description> Descriptions { get; set; }

    public Item()
    {
        Descriptions = new List<Description>();
    }
}

public class Description
{
    public string DescriptionText { get; set; }
    public string Country { get; set; }
}

public enum AssignmentType
{
    TypeA,
    TypeB,
    TypeC
}

Have been looking for numerous examples but so far I have not found anything addressing this. If someone have a sample or could point me in the right direction for solving this by using Reflection.Emit, it would be very appreciated.

Était-ce utile?

La solution

The simplest solution is to use CSharpCodeProvider from Microsoft.CSharp namespace:

    string source = "public class Description" +
                    "{" +
                    "   public string DescriptionText { get; set; }" +
                    "   public string Country { get; set; }" +
                    "}";

    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = false;
    parameters.GenerateInMemory = true;
    CompilerResults result = codeProvider.CompileAssemblyFromSource(parameters, source);
    if (!result.Errors.HasErrors)
    {
        Type type = result.CompiledAssembly.GetType("Description");
        var instance = Activator.CreateInstance(type);
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top