1

Reflection.Emit を使用してエンティティ グラフを動的に構築することに時間を費やしました。新しいフラット タイプ (クラス) でアセンブリを作成し、それをインスタンス化し、リフレクションで使用するのは簡単で、問題なく動作します。しかし、さらに別の動的クラスの汎用リストを使用して構造を構築するとなると、さらに複雑になり、行き詰まりました。基本的に、次の構造を動的に構築したいと思います。

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 を使用してこれを解決するための正しい方向に私を向けることができれば、非常に高く評価されます。

4

1 に答える 1

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);
    }
于 2013-11-12T22:38:00.080 に答える