Expression in .Net

 

یکی از مهمترین بخش های در  .Net ایجاد درخت Expression است. Expression Tree یک ساختمان داده که در آن هر Node یک Expression می یاشد که این اجازه با شما می دهد آنالیز، ویرایش و  در زمان Runtime کامپایل را مدیریت کنند. این قابلیت بنیادی پایه یکی از فریمورک، از جمله  Entity Framework, AutoMapper و برخی Testing Libraries است.

Using Lambda Expression

Expression<Func<int, bool>> isPositive = num => num > 0;

 

Building Expression Trees Manually

ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression zero = Expression.Constant(0, typeof(int));
BinaryExpression greaterThan = Expression.GreaterThan(numParam, zero);
Expression<Func<int, bool>> isPositive = Expression.Lambda<Func<int, bool>>(
    greaterThan,
    new ParameterExpression[] { numParam }
);

در بیاین ساختار Epression Tree را بررسی کنیم :

  • Root: LambdaEpression
  • Parameters: ParameterExpression for x and y
  • Body: BinaryExpression representing addition
  • Left: ParameterExpression for x
  • Right: ParameterExpression for y
  • NodeType: ExpressionType.Add

حال که با ساختار آنها شده ای میتوانیم ساختار درخت رو با Expression Tree بشکافیم :

Expression<Func<int, int, int>> add = (x,y) => x+y;

Console.WriteLine($"NodeType: {add.NodeType}");
Console.WriteLine($"Return Type: {add.ReturnType}");
Console.WriteLine($"Parameters: {string.Join(", ", add.Parameters.Select(p => p.Name))}");
Console.WriteLine($"Body Type: {add.Body.NodeType}");

دیدگاه شما

نشانی ایمیل شما منتشر نخواهد شد.