繁体   English   中英

在C#中映射两个类

[英]Mapping two classes in 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,但对于如何使用它或不清楚其中的大小写或下划线的选项,我并不清楚。 还是有更好的解决方案?

您的代码可以正常运行。

我个人建议您不要使用自动映射器。 关于为什么在Internet上有很多解释,例如以下示例: http : //www.uglybugger.org/software/post/friends_dont_let_friends_use_automapper

基本上,主要的问题是,如果在不修改foo2对象的情况下重命名foo1对象的某些属性,则代码将在运行时无提示地失败。

作为@ 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);

暂无
暂无

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

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