Last active
October 1, 2022 13:36
-
-
Save mr5z/7a72471eef039093c0046a2915f0ccda to your computer and use it in GitHub Desktop.
mapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using ParameterizedFunc = System.Func<object, object>; | |
namespace CompanyName.Helpers | |
{ | |
public class Mapper | |
{ | |
private readonly IDictionary<(Type, Type), ParameterizedFunc> objectDictionary = | |
new Dictionary<(Type, Type), ParameterizedFunc>(); | |
public void Register<TSource, TDestination>(Func<TSource, TDestination> mapping) | |
where TSource : class | |
where TDestination : class | |
{ | |
var key = ToKey<TSource, TDestination>(); | |
objectDictionary[key] = (arg) => mapping((TSource)arg); | |
} | |
public TDestination Map<TSource, TDestination>(TSource source) | |
where TSource : class | |
where TDestination : class | |
{ | |
var key = ToKey<TSource, TDestination>(); | |
return (TDestination)objectDictionary[key](source); | |
} | |
private (Type, Type) ToKey<TSource, TDestination>() | |
{ | |
return (typeof(TSource), typeof(TDestination)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment