Редактировал(а) Alexandr Fokin 2022/12/07 07:43

Последние авторы
1 {{code language="c#"}}
2 //Source
3 ClassA a = new ClassA()
4 {
5 A = 10,
6 B = 20
7 };
8 //Destination
9 ClassB b = new ClassB();
10
11 //Source class instance parameter
12 var parametrB = Expression.Parameter(b.GetType());
13
14 //Destination class instance parameter
15 var parametrA = Expression.Parameter(a.GetType());
16
17 var copyPropertyAEx = Expression.Assign(
18 Expression.Property(parametrB, b.GetType().GetProperty("A")),
19 Expression.Property(parametrA, a.GetType().GetProperty("A"))
20 );
21 var copyPropertyBEx = Expression.Assign(
22 Expression.Property(parametrB, b.GetType().GetProperty("B")),
23 Expression.Property(parametrA, a.GetType().GetProperty("B"))
24 );
25
26 var copyPropertyEx = Expression.Block(
27 copyPropertyAEx,
28 copyPropertyBEx
29 );
30
31 var copyPropertyDelegate = Expression
32 .Lambda<Func<ClassB, ClassA, int>>(copyPropertyEx, parametrB, parametrA)
33 .Compile();
34
35 var result = copyPropertyDelegate.Invoke(b, a);
36 {{/code}}