Reflection.Emit构建实体图

我花了一些时间尝试使用Reflection.Emit动态构建实体图。 使用新的平面类型(类)创建程序集,实例化它并使用reflection很容易并且工作正常。 但是当涉及到构建具有另一个动态类的generics列表的结构时,它变得更加复杂并且我被卡住了。 基本上,我想动态构建以下结构:

public class Head { public string HeadId { get; set; } public AssignmentType HeadType { get; set; } public int TestIndicator { get; set; } public List Items { get; set; } public Head() { Items = new List(); } } public class Item { public string ItemId { get; set; } public int Weight { get; set; } public List Descriptions { get; set; } public Item() { Descriptions = new List(); } } public class Description { public string DescriptionText { get; set; } public string Country { get; set; } } public enum AssignmentType { TypeA, TypeB, TypeC } 

一直在寻找大量的例子,但到目前为止我还没有发现任何解决这个问题的方法 如果有人有样品或者可以通过使用Reflection.Emit指出我正确的方向来解决这个问题,那将非常感激。

最简单的解决方案是使用Microsoft.CSharp命名空间中的CSharpCodeProvider

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