实现和上个用DynamicMethod的方式生成的复制实体类对应一样功能

public  static class  ExpMapper<TTarget,TSource>
    {
        
private static MapMethod<TTarget, TSource> mapMethod;
          
public static MapMethod<TTarget, TSource> GetMapMethod()
        {
            
if (mapMethod == null)
            {
                mapMethod 
= CreateMapMethod(typeof(TTarget), typeof(TSource));
            }
            
return mapMethod;
        }

        
public static TTarget Map(TSource source)
        {
            
if (mapMethod == null)
            {
                mapMethod 
= CreateMapMethod(typeof(TTarget), typeof(TSource));
            }
            
return mapMethod(source);     
        }

        
private static MapMethod<TTarget, TSource> CreateMapMethod(Type targetType, Type sourceType)
        {
            var source 
= Expression.Parameter(sourceType, "source");
   
            var binds 
= (from sp in sourceType.GetProperties()
                              from tp 
in targetType.GetProperties()
                              
where sp.Name == tp.Name
                              select Expression.Bind(tp, Expression.Property(source, sp))).ToArray();

            Expression body 
= Expression.MemberInit(Expression.New(typeof(TTarget)), binds);

            
return Expression.Lambda<MapMethod<TTarget, TSource>>(body,source).Compile();
                             
        }

    }

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2021-10-01
  • 2021-09-20
  • 2021-06-11
  • 2021-12-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-28
  • 2021-11-03
  • 2022-12-23
相关资源
相似解决方案