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]'.
答案 0 :(得分:-2)
反思是一项额外的工作,你可以在没有它的情况下实现解决方案。如果反射不是必须的,这里有几个选项。
序列化:使用 StringSerialization ( Json 或 Xml )序列化源对象和反序列化到另一个对象。< / p>
以下是另一个问题的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:映射内部类,如果属性相同,则可以跳过手动映射整个类。
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);