在c#中映射两个类
我有两节课
public class foo1 { public int id; public string image_link; public string sale_price; }
和
public class foo2 { public int Id; public string ImageLink; public string SalePrice }
属性值仅因下划线和案例而异。 我需要映射这两个类。
现在我正在尝试这样的事情及其工作:
//var b = object of foo2 var a = new foo1{ a.id = b.Id, a.image_link = b.ImageLink, a.sale_price = b.SalePrice }
我听说过AutoMapper,但我还不清楚我将如何使用它,或者忽略其中的案例或下划线的选项。 还是有更好的解决方案吗?
您的代码很好,并按预期工作。
我个人建议你不要使用automapper。 关于为什么在互联网上有很多解释,例如一个: http : //www.uglybugger.org/software/post/friends_dont_let_friends_use_automapper
基本上,主要问题是如果在foo1
对象上重命名某个属性而不修改foo2
对象,则代码将在运行时静默失败。
正如@ ken2k的回答,我建议你不要使用对象映射器。
如果要保存代码,可以只为映射创建一个新方法(或直接在构造函数中)。
public class foo1 { public int id; public string image_link; public string sale_price; public void map(foo2 obj) { this.id = obj.Id; this.image_link = obj.ImageLink; this.sale_price = obj.SalePrice; } }
然后
//var b = object of foo2 var a = new foo1(); a.map(b);