如何通过在 C# 中生成 IL 将 Action<T> 转换为编译表达式或 DynamicMethod?

How do I turn an Action<T> to a Compiled Expression or a DynamicMethod by generating IL in C#?

我必须处理维护一个库,该库允许用户针对它注册一个通用处理程序 (Action<T>),稍后一旦它收到一个事件,它就会通过每个注册的处理程序并传递它们事件。为了使问题简短,让我们跳过这样做的原因。

由于这种设计,我们必须在传递每个事件时调用 DynamicInvoke;这被证明非常慢,因此需要使用 IL 生成将委托转换为 CompiledExpression 或 DynamicMethod。我已经看到了为 PropertyGetters (Matt Warren's excellent article) 实现此功能的各种示例,但我无法让它与 Action<T> 一起使用,其中 T 可以是 ValueType 或 ReferenceType。

这是一个当前(缓慢的)工作示例(为简洁起见进行了简化):

void Main()
{
    var producer = new FancyEventProduder();
    var fancy = new FancyHandler(producer);
    
    fancy.Register<Base>(x => Console.WriteLine(x));
    producer.Publish(new Child());  
}

public sealed class FancyHandler
{
    private readonly List<Delegate> _handlers;
    
    public FancyHandler(FancyEventProduder produer)
    {
        _handlers = new List<Delegate>();
        produer.OnMessge += OnMessage;
    }

    public void Register<T>(Action<T> handler) => _handlers.Add(handler);

    private void OnMessage(object sender, object payload)
    {
        Type payloadType = payload.GetType();
        foreach (Delegate handler in _handlers)
        {
            // this could be cached at the time of registration but has negligable impact
            Type delegParamType = handler.Method.GetParameters()[0].ParameterType;
            if(delegParamType.IsAssignableFrom(payloadType))
            {
                handler.DynamicInvoke(payload);
            }           
        }
    }
}

public sealed class FancyEventProduder
{
    public event EventHandler<object> OnMessge;
    
    public void Publish(object payload) => OnMessge?.Invoke(this, payload);
}

public class Base { }
public sealed class Child : Base { }

不确定这是否是个好主意:

public sealed class FancyHandler
{
    private readonly List<Tuple<Delegate, Type, Action<object>>> _handlers = new List<Tuple<Delegate, Type, Action<object>>>();

    public FancyHandler(FancyEventProduder produer)
    {
        produer.OnMessge += OnMessage;
    }

    public void Register<T>(Action<T> handler)
    {
        _handlers.Add(Tuple.Create((Delegate)handler, typeof(T), BuildExpression(handler)));
    }

    private static Action<object> BuildExpression<T>(Action<T> handler)
    {
        var par = Expression.Parameter(typeof(object));
        var casted = Expression.Convert(par, typeof(T));
        var call = Expression.Call(Expression.Constant(handler.Target), handler.Method, casted);
        var exp = Expression.Lambda<Action<object>>(call, par);
        return exp.Compile();
    }

    private void OnMessage(object sender, object payload)
    {
        Type payloadType = payload.GetType();

        foreach (var handlerDelegate in _handlers)
        {
            // this could be cached at the time of registration but has negligable impact
            Type delegParamType = handlerDelegate.Item2;
                
            if (delegParamType.IsAssignableFrom(payloadType))
            {
                handlerDelegate.Item3(payload);
            }
        }
    }
}

请注意,即使不使用表达式树,也可以重复使用一些较小的想法:例如保存 typeof(T) 而不是多次调用 handler.Method.GetParameters()[0].ParameterType

一些测试用例:

fancy.Register<Base>(x => Console.WriteLine($"Base: {x}"));
fancy.Register<Child>(x => Console.WriteLine($"Child: {x}"));
fancy.Register<object>(x => Console.WriteLine($"object: {x}"));
fancy.Register<long>(x => Console.WriteLine($"long: {x}"));
fancy.Register<long?>(x => Console.WriteLine($"long?: {x}"));
fancy.Register<int>(x => Console.WriteLine($"int: {x}"));
fancy.Register<int?>(x => Console.WriteLine($"int?: {x}"));

producer.Publish(new Base());
producer.Publish(new Child());
producer.Publish(5);

完整表达式树(类型检查移至表达式树内部,其中 as 代替 IsAssignableFrom

public sealed class FancyHandler
{
    private readonly List<Action<object>> _handlers = new List<Action<object>>();

    public FancyHandler(FancyEventProduder produer)
    {
        produer.OnMessge += OnMessage;
    }

    public void Register<T>(Action<T> handler)
    {
        _handlers.Add(BuildExpression(handler));
    }

    private static Action<object> BuildExpression<T>(Action<T> handler)
    {
        if (typeof(T) == typeof(object))
        {
            return (Action<object>)(Delegate)handler;
        }

        var par = Expression.Parameter(typeof(object));

        Expression body;

        if (typeof(T).IsValueType)
        {
            // We remove the nullable part of value types
            Type type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

            var unbox = Expression.Unbox(par, typeof(T));
            body = Expression.IfThen(Expression.TypeEqual(par, type), Expression.Call(Expression.Constant(handler.Target), handler.Method, unbox));

            if (type != typeof(T))
            {
                // Nullable type
                // null with methods that accept nullable type: call the method
                body = Expression.IfThenElse(Expression.Equal(par, Expression.Constant(null)), Expression.Call(Expression.Constant(handler.Target), handler.Method, Expression.Constant(null, typeof(T))), body);
            }
        }
        else
        {
            // Imagine the resulting code will be:

            // (object par) => 
            // {
            //     if (par == null)
            //     {
            //         handler(null);
            //     }
            //     else
            //     {
            //         T local;
            //         local = par as T;
            //         if (local != null)
            //         {
            //             handler(local);
            //         }
            //     }
            // }

            var local = Expression.Variable(typeof(T));
                
            var typeAs = Expression.Assign(local, Expression.TypeAs(par, typeof(T)));

            var block = Expression.Block(new[]
            {
                local,
            },
            new Expression[]
            {
                typeAs,
                Expression.IfThen(Expression.NotEqual(typeAs, Expression.Constant(null)), Expression.Call(Expression.Constant(handler.Target), handler.Method, typeAs))
            });

            // Handling case par == null, call the method
            body = Expression.IfThenElse(Expression.Equal(par, Expression.Constant(null)), Expression.Call(Expression.Constant(handler.Target), handler.Method, Expression.Constant(null, typeof(T))), block);
        }

        var exp = Expression.Lambda<Action<object>>(body, par);
        return exp.Compile();
    }

    private void OnMessage(object sender, object payload)
    {
        foreach (var handlerDelegate in _handlers)
        {
            handlerDelegate(payload);
        }
    }
}

这个版本甚至支持null:

producer.Publish(null);

第三个版本,基于@BorisB 的想法,这个版本避免使用 Expression 并直接使用委托。它应该有更短的预热时间(没有 Expression 树被编译)。仍然有一个小的反射问题,但幸运的是这个问题只在添加新的处理程序时出现(有注释解释它)。

public sealed class FancyHandler
{
    private readonly List<Action<object>> _handlers = new List<Action<object>>();

    public FancyHandler(FancyEventProduder produer)
    {
        produer.OnMessge += OnMessage;
    }

    public void Register<T>(Action<T> handler)
    {
        if (typeof(T).IsValueType)
        {
            _handlers.Add(BuildExpressionValueType(handler));
        }
        else
        {
            // Have to use reflection here because the as operator requires a T is class
            // this check is bypassed by using reflection
            _handlers.Add((Action<object>)_buildExpressionReferenceTypeT.MakeGenericMethod(typeof(T)).Invoke(null, new[] { handler }));
        }
    }

    private static Action<object> BuildExpressionValueType<T>(Action<T> handler)
    {
        // We remove the nullable part of value types
        Type type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

        if (type == typeof(T))
        {
            // Non nullable
            return (object par) =>
            {
                if (par is T)
                {
                    handler((T)par);
                }
            };
        }

        // Nullable type
        return (object par) =>
        {
            if (par == null || par is T)
            {
                handler((T)par);
            }
        };
    }

    private static readonly MethodInfo _buildExpressionReferenceTypeT = typeof(FancyHandler).GetMethod(nameof(BuildExpressionReferenceType), BindingFlags.Static | BindingFlags.NonPublic);

    private static Action<object> BuildExpressionReferenceType<T>(Action<T> handler) where T : class
    {
        if (typeof(T) == typeof(object))
        {
            return (Action<object>)(Delegate)handler;
        }

        return (object par) =>
        {
            if (par == null)
            {
                handler((T)par);
            }
            else
            {
                T local = par as T;

                if (local != null)
                {
                    handler(local);
                }
            }
        };
    }

    private void OnMessage(object sender, object payload)
    {
        foreach (var handlerDelegate in _handlers)
        {
            handlerDelegate(payload);
        }
    }
}