如何从List to list using reflection? C#复制

问题描述 投票:0回答:1

两个对象都“相同”,但我不可能直接复制对象定义。

A类看起来像:

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

B级看起来像:

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

如您所见,唯一的区别是属性和命名空间,两个类具有相同的方法和属性。

我正在使用反射的错误就是这个

“System.Collections.Generic.List1 [Namespace.Property]”类型的对象无法转换为“System.Collections.Generic.List1 [MyNames.Property]”类型。

c# list reflection
1个回答
-2
投票

反思是一项额外的工作,你可以在没有它的情况下实现解决方案。如果反射不是必须的,这里有几个选项。

序列化:使用StringSerialization(Json或Xml)序列化源对象和反序列化为另一个。

这是另一个问题的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:映射内部类,如果属性相同,则可以跳过手动映射整个类。

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);
© www.soinside.com 2019 - 2024. All rights reserved.