Сценарии
Версия 1.3 от Alexandr Fokin на 2022/06/15 12:57
Компиляция дерева в делегат
Expression
.Lambda(expressionValiarble)
.Compile();
.Lambda(expressionValiarble)
.Compile();
Простое копирование свойств одного класса в другой
//Source
ClassA a = new ClassA()
{
A = 10,
B = 20
};
//Destination
ClassB b = new ClassB();
//Source class instance parameter
var parametrB = Expression.Parameter(b.GetType());
//Destination class instance parameter
var parametrA = Expression.Parameter(a.GetType());
var copyPropertyAEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("A")),
Expression.Property(parametrA, a.GetType().GetProperty("A"))
);
var copyPropertyBEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("B")),
Expression.Property(parametrA, a.GetType().GetProperty("B"))
);
var copyPropertyEx = Expression.Block(
copyPropertyAEx,
copyPropertyBEx
);
var copyPropertyDelegate = Expression
.Lambda<Func<ClassB, ClassA, int>>(copyPropertyEx, parametrB, parametrA)
.Compile();
var result = copyPropertyDelegate.Invoke(b, a);
ClassA a = new ClassA()
{
A = 10,
B = 20
};
//Destination
ClassB b = new ClassB();
//Source class instance parameter
var parametrB = Expression.Parameter(b.GetType());
//Destination class instance parameter
var parametrA = Expression.Parameter(a.GetType());
var copyPropertyAEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("A")),
Expression.Property(parametrA, a.GetType().GetProperty("A"))
);
var copyPropertyBEx = Expression.Assign(
Expression.Property(parametrB, b.GetType().GetProperty("B")),
Expression.Property(parametrA, a.GetType().GetProperty("B"))
);
var copyPropertyEx = Expression.Block(
copyPropertyAEx,
copyPropertyBEx
);
var copyPropertyDelegate = Expression
.Lambda<Func<ClassB, ClassA, int>>(copyPropertyEx, parametrB, parametrA)
.Compile();
var result = copyPropertyDelegate.Invoke(b, a);
Вызов делегаты при построении EpressionTree
Expression Trees and Invoking a Delegate
https://stackoverflow.com/questions/2215712/expression-trees-and-invoking-a-delegate
Объявлений локальной переменной в блоке (без передачи извне)
https://question-it.com/questions/717473/peremennaja-tipa-ukazana-iz-oblasti-vidimosti-no-ne-opredelena