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

后端 未结 7 518
野的像风
野的像风 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:12

    If you can add a method to the metadata class you could do something like the following

    public class Foo
    {
        public string Name { get; set; }
        public void SerializeWithMetadata(Bar bar)
        {
           var obj = new {
                           Name = this.Name,
                           Guid = bar.Guid,
                           Property1 = Bar.Property1
                          }
           //Serialization code goes here
        }
    }
    
    public class Bar
    {
        public Guid Id { get; set; }
        public string Property1 { get; set; }
        public string Property2 { get; set; }
        public string Property3 { get; set; }
        public string Property4 { get; set; }
    }
    

    I'm not sure I would recommend this exact approach I mainly left it here to display anonymous types as a possible option that might be worth exploring

提交回复
热议问题