且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建使用表达式树空的代表?

更新时间:2023-02-16 13:04:35

事实证明它不是的的许多工作使用 Expression.Lambda()。不过,我仍然有兴趣有可能其他的答案

As it turns out it isn't that much work using Expression.Lambda(). However, I'm still interested in possible other answers.

我确实需要一个辅助方法,我以前写的:

I did need a helper method which I wrote previously:

/// <summary>
///   The name of the Invoke method of a Delegate.
/// </summary>
const string InvokeMethod = "Invoke";

/// <summary>
///   Get method info for a specified delegate type.
/// </summary>
/// <param name = "delegateType">The delegate type to get info for.</param>
/// <returns>The method info for the given delegate type.</returns>
public static MethodInfo MethodInfoFromDelegateType( Type delegateType )
{
    Contract.Requires(
        delegateType.IsSubclassOf( typeof( MulticastDelegate ) ),
        "Given type should be a delegate." );

    return delegateType.GetMethod( InvokeMethod );
}

当你的 EventInfo 可以为它创建一个空的lambda如下

When you have EventInfo you can create an empty lambda for it as follows:

EventInfo _event;

...

MethodInfo delegateInfo
    = DelegateHelper.MethodInfoFromDelegateType( _event.EventHandlerType );
ParameterExpression[] parameters = delegateInfo
    .GetParameters()
    .Select( p => Expression.Parameter( p.ParameterType ) )
    .ToArray();
Delegate emptyDelegate = Expression.Lambda(
    _event.EventHandlerType,
    Expression.Empty(), "EmptyDelegate", true, parameters ).Compile();