如果项目等效,则将项目从一个类映射到另一类 [英] Mapping items from one class to another if Items are equivalent
问题描述
说我有一个看起来像这样的class
:
Say I have one class
that looks like this:
public class Person
{
public string Name {get; set;}
public int Number {get; set;}
}
另一个看起来像这样:
public class Dog
{
public string Name {get; set;}
public int Number {get; set;}
}
它们是两个不同的类,但是它们恰好具有完全相同的元素(称为Name
的字符串和称为Number
的整数)
They are two different classes, but they happen to have the exact same elements (a string called Name
and an int called Number
)
如果我有一个Person
实例,然后用相同的Name
和Number
创建一个Dog
实例,那么C#中是否有一种简便的方法?
Is there an easy way in C# to, say, if I had an instance of Person
to then create an instance of Dog
with the same Name
and Number
?
例如,如果我有:
Person person = new Person();
person.Name = "George";
person.Number = 1;
我知道我不能简单地去:
I know I can't simply go:
Dog dog = person;
因为它们是两种不同的类型.但是C#中有一种方法可以检查哦,如果它们具有相同的元素,请将Dog
的相同元素设置为等于Person
的元素.
但是我觉得必须比做类似的事情更简单的方法:
Because they are two different types. But is there a way in C# to check "oh, if they have the same element, set the same elements of Dog
to equal that of Person
.
But I feel there has to be an easier way than doing something like:
dog.Name = person.Name;
dog.Number = person.Number;
尤其是如果类具有很多元素.另外,如果有人想知道,这两个不同的类位于API的两个不同部分中,因此我不能简单地使它们彼此相关.
Especially if the class has a LOT of elements. Also if anyone is wondering, these two different classes are in two different pieces of the API, so I can't simply make them related either.
推荐答案
您可以使用 AutoMapper :
public Dog UsingAMR(Person prs)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Person, Dog>();
});
IMapper mapper = config.CreateMapper();
return mapper.Map<Person, Dog>(prs);
}
那么您可以轻松地:
Person ps = new Person {Name = "John", Number = 25};
Dog dog = UsingAMR(ps);
别忘了先按照参考资料中所述从包管理器控制台先安装AutoMapper
:
Just don't forget to install AutoMapper
first from the package manager console as mentioned in the reference:
- 从工具菜单中单击 NuGet软件包管理器 ==> 软件包管理器控制台
-
然后键入以下命令:
- From Tools menu click on NuGet Package Manager ==> Package Manager Console
Then type the following command:
PM> Install-Package AutoMapper
这篇关于如果项目等效,则将项目从一个类映射到另一类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!