1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| using System;
using System.Linq.Expressions;
...
public static class Operators<T>
{
private static readonly Func<T, T, T> _add;
private static readonly Func<T, T, T> _subtract;
private static readonly Func<T, T, T> _multiply;
private static readonly Func<T, T, T> _divide;
static Operators()
{
_add = CreateBinaryOperator(ExpressionType.Add);
_subtract = CreateBinaryOperator(ExpressionType.Subtract);
_multiply = CreateBinaryOperator(ExpressionType.Multiply);
_divide = CreateBinaryOperator(ExpressionType.Divide);
}
private static Func<T, T, T> CreateBinaryOperator(ExpressionType expressionType)
{
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
var body = Expression.MakeBinary(expressionType, x, y);
var expr = Expression.Lambda<Func<T, T, T>>(body, x, y);
return expr.Compile();
}
public static T Add(T x, T y)
{
return _add(x, y);
}
public static T Subtract(T x, T y)
{
return _subtract(x, y);
}
public static T Multiply(T x, T y)
{
return _multiply(x, y);
}
public static T Divide(T x, T y)
{
return _divide(x, y);
}
} |
Partager