Merging anonymous types

前端 未结 4 467
孤街浪徒
孤街浪徒 2020-12-08 06:47

How can I merge two anonymous types, so that the result contains the properties of both source objects?

var source1 = new
{
    foo = \"foo\",
    bar = \"ba         


        
4条回答
  •  盖世英雄少女心
    2020-12-08 07:28

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Dynamic;
    
    namespace ConsoleApplication1
    {
      class Program
      {
         static void Main(string[] args)
         {
            var source1 = new
            {
                foo = "foo",
                bar = "bar"
            };
    
            var source2 = new
            {
               baz = "baz"
            };
    
            dynamic merged = Merge(source1, source2);
    
            Console.WriteLine("{0} {1} {2}", merged.foo, merged.bar, merged.baz);
         }
    
         static MergedType Merge(T1 t1, T2 t2)
         {
            return new MergedType(t1, t2);
         }
      }
    
      class MergedType : DynamicObject
      {
         T1 t1;
         T2 t2;
         Dictionary members = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
    
         public MergedType(T1 t1, T2 t2)
         {
            this.t1 = t1;
            this.t2 = t2;
            foreach (System.Reflection.PropertyInfo fi in typeof(T1).GetProperties())
            {
               members[fi.Name] = fi.GetValue(t1, null);
            }
            foreach (System.Reflection.PropertyInfo fi in typeof(T2).GetProperties())
            {
               members[fi.Name] = fi.GetValue(t2, null);
            }
         }
    
         public override bool TryGetMember(GetMemberBinder binder, out object result)
         {
            string name = binder.Name.ToLower();
            return members.TryGetValue(name, out result);
         }
      }
    }
    

提交回复
热议问题