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

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

    UNTESTED, but using the Reflection.Emit API, something like this should work:

    public Type MergeTypes(params Type[] types)
    {
        AppDomain domain = AppDomain.CurrentDomain;
        AssemblyBuilder builder = 
            domain.DefineDynamicAssembly(new AssemblyName("CombinedAssembly"),
            AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = builder.DefineDynamicModule("DynamicModule");
        TypeBuilder typeBuilder = moduleBuilder.DefineType("CombinedType");
        foreach (var type in types)
        {
            var props = GetProperties(type);
            foreach (var prop in props)
            {
                typeBuilder.DefineField(prop.Key, prop.Value, FieldAttributes.Public);
            }
        }
    
        return typeBuilder.CreateType();
    
    
    }
    
    private Dictionary GetProperties(Type type)
    {
        return type.GetProperties().ToDictionary(p => p.Name, p => p.PropertyType);
    }
    

    USAGE:

    Type combinedType = MergeTypes(typeof(Foo), typeof(Bar));
    

提交回复
热议问题