[英]Generic custom method to convert one object type to another in c#
I, am trying to implement a generic method to convert one object to another object in c#.我正在尝试实现一种通用方法,将一个对象转换为 C# 中的另一个对象。
Here is the some code I tried这是我试过的一些代码
public interface IDTOMapper<TSource, TDestination>
{
TDestination Convert(TSource source_object);
}
public class DtoMapper<TSource, TDestination> : IDTOMapper<TSource, TDestination>
{
public TDestination Convert(TSource source_object)
{
// How to write the code to convert one class object to another
}
}
The code which I used inside the convert method has lots of errors.Can anyone let me know how to implement with any class type objects.我在 convert 方法中使用的代码有很多错误。谁能告诉我如何使用任何类类型对象来实现。 Some example I found has specific class object conversion.
我发现的一些示例具有特定的类对象转换。
When I google I found there is auto-mapper library I, don't want to use auto-mapper library .当我谷歌我发现有auto-mapper library我不想使用auto-mapper library 。 Just want to write custom generic method
只想写自定义泛型方法
Some of the reference部分参考
Best Practices for mapping one object to another 将一个对象映射到另一个对象的最佳实践
https://softwareengineering.stackexchange.com/questions/301580/best-practices-regarding-type-mapping-and-extension-methods https://softwareengineering.stackexchange.com/questions/301580/best-practices-regarding-type-mapping-and-extension-methods
Generic method to map objects of different types 映射不同类型对象的通用方法
https://www.codeproject.com/Tips/781202/Csharp-Custom-Mapperhttps://www.codeproject.com/Tips/781202/Csharp-Custom-Mapper
You say you don't want to use an auto-mapper, but what you're trying to write is the same thing.您说您不想使用自动映射器,但是您尝试编写的内容是相同的。 You're just going to reinvent the wheel and write your own auto-mapper.
您只需重新发明轮子并编写自己的自动映射器。
I strongly suggest using an existing library like AutoMapper.我强烈建议使用像 AutoMapper 这样的现有库。 It'll be faster and have less bugs.
它会更快,错误更少。
If not that, then I myself would avoid trying to automate this task.如果不是这样,那么我自己会避免尝试自动执行此任务。 For each ViewModel class, add a method
CopyFromBusiness
and write the copying code there yourself by hand.对于每个 ViewModel 类,添加一个方法
CopyFromBusiness
并自己手动编写复制代码。 Yes, it's quite repetitive, but writing your own auto-mapper will be nearly as much work and the result will invariably be poorer than an existing library.是的,这是相当重复的,但是编写自己的自动映射器的工作量几乎一样多,结果总是比现有的库更差。 A manually written
CopyFromBusiness
method will be the fastest possible option (at runtime) and in the future the code will be a lot easier to maintain because there will not be any hidden magic.手动编写的
CopyFromBusiness
方法将是最快的选择(在运行时),将来代码将更容易维护,因为不会有任何隐藏的魔法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.