What is the best way to merge two objects during runtime using C#?

后端 未结 7 531
野的像风
野的像风 2021-02-06 10:18

I have two objects and I want to merge them:

public class Foo
{
    public string Name { get; set; }
}

public class Bar
{
    public Guid Id { get; set; }
    p         


        
7条回答
  •  爱一瞬间的悲伤
    2021-02-06 11:11

    Aside from the question "Why", the only way I can think to take two objects, one known and one unknown, and combine them into a new type would be to use Reflection.Emit to generate a new type at runtime.

    There are examples on MSDN. You would have to determine weather you wanted to merge fields that had the same name or have the known type supersede the unknown type.

    As far as I can tell, there is no way to do this in LINQ.

    Since all you're interested in is Properties it should be pretty easy to use this article as an example. Leave out the il for creating methods and you're good to go.

提交回复
热议问题