Cast one object to another

你离开我真会死。 提交于 2020-01-14 10:03:45

问题


I have got two user defined CLR objects which are identical and only differ in name, for example this code:

public class Person
{
  public string Name { get; set; }
  public string Address { get; set; }
  public string LastName { get; set; }
  public string ETC { get; set; }
}

public class PersonData
{
  public string Name { get; set; }
  public string Address { get; set; }
  public string LastName { get; set; }
  public string ETC { get; set; }
}

I know that this can be done by creating an object from either of these CLR's and than pass all properties one by one to it.

But is there another way? I got a few CLR's that are pretty big, 15+ properties.

[Edit] Some more context. The classes where already there. I generated a model from the database using EntityFramework. The database has almost the exact same structure as the classes.

Also, it's a lot of code that was already there. These classes also inherit from several interfaces etc. Refactoring now is not an option, so i'm looking for an easy fix for now.


回答1:


Assumming you don't want both classes to inherit from an interface you can try Automapper it's a library for automatically mapping similar classes.




回答2:


If you are the author of those classes, you could have them implement the same interface, or even better, inherit from the same class. That way you don't have to copy values from one to another - just use a reference to their parent type. Remember, having couples of unrelated types which have exactly the same members is a sure sign that you need to rethink your design ASAP.




回答3:


And, just for the sake of completeness, here's what it looks like with reflection:

var a = new Person( ) { LastName = "lastn", Name = "name", Address = "addr", ETC = "etc" };
var b = new PersonData( );

var infoPerson = typeof( PersonData ).GetProperties( );
foreach ( PropertyInfo pi in typeof( Person ).GetProperties( ) ) {
    object value = pi.GetValue( a, null );
    infoPerson.Single( p => p.Name == pi.Name )
        .SetValue( b, value, null );
}


来源:https://stackoverflow.com/questions/18667029/cast-one-object-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!