如何使用表达式树创建一个空委托? [英] How to create an empty delegate using Expression Trees?
问题描述
使用匿名方法您可以自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 {};
如何使用表达式树?
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.
推荐答案
事实证明, t 使用 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屋!