简体   繁体   中英

How to copy from List<a> to list<b> using reflection? C#

Both object are "the same" but its imposible for me, to copy de object definition directly.

The class A looks like:

public class A { 
    [JsonProperty(PropertyName="MyPROP")]
    List<Namespace.Property> pro {get; set;}
}

The class B looks like:

public class B { 
    [JsonProperty(PropertyName="MyNewPropertyName")]
    List<MyNames.Property> pro {get; set;}
}

As you can see, the only differences are attributes and namespace, both classes has the same methods and properties.

The error I'm getting using reflection is this

El objeto de tipo 'System.Collections.Generic.List1[Namespace.Property]' no puede convertirse en el tipo 'System.Collections.Generic.List1[MyNames.Property]'.

Reflection is a lot of extra work, you can achieve a solution without it. In case reflection isn't a must, here is a few options.

Serialization: Serializing source object and Deserializing into another, using StringSerialization ( Json or Xml ).

Here is Brian Rogers code on another question, that ignores JsonPropertyAttribute .

class LongNameContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        // Let the base class create all the JsonProperties 
        // using the short names
        IList<JsonProperty> list = base.CreateProperties(type, memberSerialization);

        // Now inspect each property and replace the 
        // short name with the real property name
        foreach (JsonProperty prop in list)
        {
            prop.PropertyName = prop.UnderlyingName;
        }

        return list;
    }
}

AutoMapper: Mapping the inner classes, and if your properties are the same, you can skip manually mapping the entire classes.

Complete Fiddle

Mapper.Initialize(cfg => cfg.CreateMap<A, B>().ReverseMap());

var objA = new A
{
    Prop = new List<AClass>
    {
        new AClass { Name = "Magneto" },
        new AClass { Name = "Wolverine" }
    }
};

var objB = Mapper.Map<B>(objA);
Console.WriteLine(objB.Prop[0].Name);
Console.WriteLine(objB.Prop[1].Name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM