Created
September 10, 2023 09:11
-
-
Save habib-sadullaev/b85fc58cfa02340583f09e195332ede3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Linq.Expressions; | |
static class _ | |
{ | |
static void Deconstruct(this BinaryExpression x, | |
out ExpressionType type, | |
out Expression left, | |
out Expression right) | |
{ | |
(type, left, right) = (x.NodeType, x.Left, x.Right); | |
} | |
static void Main() | |
{ | |
Expression<Func<int, int>> expr = x => x + 5; | |
expr = Replace(expr); | |
var res = expr.Compile()(5); | |
Console.WriteLine(res); | |
} | |
public static Expression<Func<T, T>> Replace<T>( | |
Expression<Func<T, T>> node) | |
{ | |
var body = node.Body switch | |
{ | |
BinaryExpression(ExpressionType.Add, var left, _) => | |
Expression.MakeBinary(ExpressionType.Multiply, left, left), | |
Expression e => e | |
}; | |
return Expression.Lambda<Func<T, T>>(body, node.Parameters); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment