.Net 创建可以通过反射传递给方法<T>的对象

问题描述 投票:0回答:1

目前我有自定义映射器,它接受

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 是变量,但像类型一样使用”。谢谢

.net reflection
1个回答
0
投票

抛开为什么要实现自定义映射器,当有很多可用的解决方案时,您可以尝试以下操作:

    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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.