问题
I have two classes
public class foo1
{
public int id;
public string image_link;
public string sale_price;
}
and
public class foo2
{
public int Id;
public string ImageLink;
public string SalePrice
}
The property values differ only by underscore and cases. I need to map these two classes.
For now I am trying something like this and its working:
//var b = object of foo2
var a = new foo1{
a.id = b.Id,
a.image_link = b.ImageLink,
a.sale_price = b.SalePrice
}
I heard of AutoMapper, but I din't have clear idea of how i am going to use that or where is the option of ignoring cases or underscores in it. or is there any better solution to it?
回答1:
Your code is fine and works as expected.
I would personally advise you to not use automapper. There are plenty explanations about why on the Internet, here's for example one: http://www.uglybugger.org/software/post/friends_dont_let_friends_use_automapper
Basically the major issue is that your code will silently fail at runtime if you rename some property on your foo1
object without modifying your foo2
object.
回答2:
As @ken2k answer, I suggest you to don't use an object mapper.
If you want to save code you can just create a new method (or directly in the constructor) for the mapping.
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;
}
}
Then
//var b = object of foo2
var a = new foo1();
a.map(b);
来源:https://stackoverflow.com/questions/32458970/mapping-two-classes-in-c-sharp