美好的一天,我认为最好的方法是使用泛型如下:
public class FooResolver<TSource, TDestination> : IValueResolver<TSource, TDestination, string>
{
private readonly Dictionary<Type, int> typeDictionary;
public FooResolver()
{
typeDictionary = new Dictionary<Type, int>
{
{typeof(FooA), 0},
{typeof(FooB), 1}
};
}
pulic string Resolve(TSource source, TDestination destination, string destMember,
ResolutionContext context)
{
switch (typeDictionary[source.GetType()])
{
case 0:
var fooA = ((FooA)Convert.ChangeType(source, typeof(FooA)));
//custom code
break;
case 1:
var fooB = ((FooB)Convert.ChangeType(source, typeof(FooB)));
//custom code
break;
}
return string_value;
}
}
在映射期间,您只需提供源和目标的实际类型,例如
act.MapFrom<FooResolver<FooA, FooADestination>>