Reflection.Emit Constructing an Entity Graph

I spent some time creating a dynamic object using Reflection.Emit. Creating an assembly with a new flat type (class), instantiating and using it with reflection is easy and excellent. But when it comes to building a structure with generic lists of another dynamic class, it gets harder and I'm stuck. Basically, I would like to dynamically build the following structure:

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
}

We searched for numerous examples, but so far I have not found anything that would concern this. If anyone has a sample or I can point me in the right direction to solve this problem with Reflection.Emit, it would be very helpful.

+1
source share
1

CSharpCodeProvider Microsoft.CSharp:

    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);
    }
+1

Source: https://habr.com/ru/post/1547178/


All Articles