使用表達式目錄樹實現兩個不同類型的屬性賦值:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
public class People { public int Age { get; set; } public string Name { get; set; } public int Id; } public class PeopleCopy { public int Age { get; set; } public string Name { get; set; } public int Id; } public class Class1 { private static Dictionary< string , object> _Dic = new Dictionary< string , object>(); private static TOut TransExp< TIn , TOut>(TIn tIn) { string key = $"funckey_{typeof(TIn).FullName}_{typeof(TOut).FullName}"; if (!_Dic.Keys.Contains(key)) { ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p"); List< MemberBinding > memberBindingList = new List< MemberBinding >(); foreach (var item in typeof(TOut).GetProperties()) { PropertyInfo propertyInfo = typeof(TIn).GetProperty(item.Name); if (propertyInfo == null) { continue; } MemberExpression property = Expression.Property(parameterExpression, propertyInfo); memberBindingList.Add(Expression.Bind(item, property)); } foreach (var item in typeof(TOut).GetFields()) { FieldInfo fieldInfo = typeof(TIn).GetField(item.Name); if (fieldInfo == null) { continue; } MemberExpression property = Expression.Field(parameterExpression, fieldInfo); memberBindingList.Add(Expression.Bind(item, property)); } Expression< Func <TIn, TOut>> expression = Expression.Lambda< Func <TIn, TOut>>(Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList), new ParameterExpression[] { parameterExpression }); Func< TIn , TOut> func = expression.Compile(); _Dic.Add(key,func); } return ((Func < TIn , TOut > )_Dic[key])(tIn); } } static void Main(string[] args) { List< ClassLibrary1.PeopleCopy > PeoleCopyList = new List< ClassLibrary1.PeopleCopy >(); for (int i = 0; i < 5 ; i++) { ClassLibrary1.People people = new ClassLibrary1.People() { Id = 5 +1, Age = 25 , Name = "aaa" +i }; PeoleCopyList.Add(Class1.ToutGet<ClassLibrary1.People, ClassLibrary1.PeopleCopy>(people)); } } |
以上這篇C# 表達式目錄樹的應用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/Torey/archive/2017/12/16/8048131.html