使用表达式目录树实现两个不同类型的属性赋值:
People类:

1 public class People 2 { 3 public int Age { get; set; } 4 public string Name { get; set; } 5 6 public int Id; 7 8 }
PeopleCopy类:

1 namespace ConsoleApp2 2 { 3 public class PeopleCopy 4 { 5 public int Age { get; set; } 6 public string Name { get; set; } 7 8 public int Id; 9 10 public override string ToString() 11 { 12 return "Age="+Age+";Name="+Name+";Id="+Id; 13 } 14 } 15 }
实现类型属性赋值:ExpressionTree类

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Linq.Expressions; 5 using System.Reflection; 6 7 namespace ConsoleApp1 8 { 9 public class Class1 10 { 11 12 private static Dictionary<string, object> _Dic = new Dictionary<string, object>(); 13 private static TOut TransExp<TIn, TOut>(TIn tIn) 14 { 15 string key = $"funckey_{typeof(TIn).FullName}_{typeof(TOut).FullName}"; 16 if (!_Dic.Keys.Contains(key)) 17 { 18 ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); 19 List<MemberBinding> memberBindingList = new List<MemberBinding>(); 20 foreach (var item in typeof(TOut).GetProperties()) 21 { 22 PropertyInfo propertyInfo = typeof(TIn).GetProperty(item.Name); 23 if (propertyInfo == null) { continue; } 24 MemberExpression property = Expression.Property(parameterExpression, propertyInfo); 25 memberBindingList.Add(Expression.Bind(item, property)); 26 } 27 foreach (var item in typeof(TOut).GetFields()) 28 { 29 FieldInfo fieldInfo = typeof(TIn).GetField(item.Name); 30 if (fieldInfo == null) { continue; } 31 MemberExpression property = Expression.Field(parameterExpression, fieldInfo); 32 memberBindingList.Add(Expression.Bind(item, property)); 33 } 34 Expression<Func<TIn, TOut>> expression = Expression.Lambda<Func<TIn, TOut>>(Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList), new ParameterExpression[] 35 { 36 parameterExpression 37 }); 38 Func<TIn, TOut> func = expression.Compile(); 39 _Dic.Add(key, func); 40 } 41 return ((Func<TIn, TOut>)_Dic[key])(tIn); 42 } 43 44 } 45 }
测试:Program类:

1 using System; 2 using System.Collections.Generic; 3 4 namespace ConsoleApp2 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 11 List<PeopleCopy> peoleCopyList = new List<PeopleCopy>(); 12 for (int i = 0; i < 5; i++) 13 { 14 People people = new People() { Id = 5 + 1, Age = 25, Name = "aaa" + i }; 15 peoleCopyList.Add(ExpressionTree.TransExp<People, PeopleCopy>(people)); 16 } 17 foreach (var item in peoleCopyList) 18 { 19 Console.WriteLine(item); 20 } 21 Console.Read(); 22 } 23 } 24 }
结果如下:
ExpressionTreeVisualize for vs2017
Expression Tree Visualizer 是一个集成在Visual Studio中的工具,用于在运行时以树状结构显示出指定的Expression。