Сценарии

Версия 1.2 от Alexandr Fokin на 2022/06/15 12:57

Компиляция дерева в делегат

Expression
    .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);