Reflection.Emit的大厦有实体图 [英] Reflection.Emit Building a entity graph
问题描述
我花了一些时间试图与Reflection.Emit的动态建立的实体图。创建一个新的平板类型(类),实例并与反射使用它装配简单,工作正常。但是,当涉及到建筑结构又一动态类的泛型列表,它变得更复杂,我被困。基本上,我想动态生成的结构如下:
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
}
一直在寻找的例子不胜枚举,但到目前为止,我还没有发现任何解决该问题。如果有人有一个样品或可以点我在正确的方向通过使用Reflection.Emit的解决这个,这将是非常赞赏。
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.
推荐答案
最简单的解决方法是使用 CSharpCodeProvider
从 Microsoft.CSharp
命名空间:
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);
}
这篇关于Reflection.Emit的大厦有实体图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!