如何创建使用表达式树空的代表? [英] How to create an empty delegate using Expression Trees?

查看:146
本文介绍了如何创建使用表达式树空的代表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 您可以创建自空的代表匿名方法。C#2.0

Using anonymous methods you can create empty delegates since C# 2.0.

public event EventHandler SomeEvent = delegate {};
public event Action OtherEvent = delegate {};

这是如有用以防止被调用的事件的时候做的空检查。

This is e.g. useful to prevent having to do the null check when invoking events.

如何创建使用表达式树一样的行为

How can I create the same behavior using Expression Trees?

唯一可能的选项我现在看到的是使用的 Expression.Lambda() ,但据我可以告诉这将需要很多额外的工作。

The only possible option I see now is to use Expression.Lambda(), but as far as I can tell this would require a lot of extra work.

推荐答案

事实证明它不是的的许多工作使用 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();

这篇关于如何创建使用表达式树空的代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆