目前我有自定义映射器,它接受
TSource
和 TDestination
;
public static TDestination Map<TSource, TDestination>(TSource sourceObject)
{
var destinationObject = Activator.CreateInstance<TDestination>();
if (sourceObject != null)
{
foreach (var sourceProperty in typeof(TSource).GetProperties())
{
var destinationProperty = typeof(TDestination).GetProperty(sourceProperty.Name);
destinationProperty?.SetValue(destinationObject, sourceProperty.GetValue(sourceObject));
}
}
return destinationObject;
}
这很好,直到遇到
List
。所以我像这样扩展了映射器
public static TDestination Map<TSource, TDestination>(TSource sourceObject)
{
var destinationObject = Activator.CreateInstance<TDestination>();
if (sourceObject != null)
{
foreach (var sourceProperty in typeof(TSource).GetProperties())
{
var destinationProperty = typeof(TDestination).GetProperty(sourceProperty.Name);
If (//check for list)
{
var sourcename = sourceProperty.ReflectedType?.FullName;
var refobj= System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(sourcename);
destinationProperty?.SetValue(destinationObject, MapToList<refobj, //destinationRefObj>(listToMap));
}
destinationProperty?.SetValue(destinationObject, sourceProperty.GetValue(sourceObject));
}
}
return destinationObject;
}
映射列表。
private static List<TDestination> MapToList<TSource, TDestination>(List<TSource> source)
{
var target = new List<TDestination>(source.Count);
foreach (var item in source)
{
//DOMAP
}
return target;
}
我如何实例化一个类,以便我可以使用它来传递给
Method<TSource, TDestination>
?我无法为此使用反射对象,因为错误是“refobj 是变量,但像类型一样使用”。谢谢
抛开为什么要实现自定义映射器,当有很多可用的解决方案时,您可以尝试以下操作:
private static List<TDestination> MapToList<TSource, TDestination>(List<TSource> source)
{
var target = new List<TDestination>(source.Count);
var addMethod = target.GetType().GetMethod("Add");
foreach (var item in source)
{
TDestination mappedObj = //DOMAP
addMethod.Invoke(target, new object[] { mappedObj });
}
return target;
}