I, am trying to implement a generic method to convert one object to another object in 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. 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 . Just want to write custom generic method
Some of the reference
Best Practices for mapping one object to another
Generic method to map objects of different types
https://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. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.