简体   繁体   English

如何<a>使用反射</a>从列表复制<a>到列表?</a> <a>C#</a>

[英]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: A类看起来像:

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

The class B looks like: B类看起来像:

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]'. 标题为“ System.Collections.Generic.List1 [Namespace.Property]”的任意转换,请参见标题为“ 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 ). 序列化:使用StringSerializationJsonXml )将源对象序列化并反序列化为另一个对象。

Here is Brian Rogers code on another question, that ignores JsonPropertyAttribute . 这是Brian Rogers关于另一个问题的代码,它忽略了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. AutoMapper:映射内部类,如果属性相同,则可以跳过手动映射整个类的操作。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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