Ste*_*ris 6 c# events delegates expression-trees
使用匿名方法,您可以创建自C#2.0以来的空委托.
public event EventHandler SomeEvent = delegate {};
public event Action OtherEvent = delegate {};
Run Code Online (Sandbox Code Playgroud)
如何使用表达式树创建相同的行为?
我现在看到的唯一可能的选择是使用Expression.Lambda(),但据我所知,这将需要大量的额外工作.
表达树,就其目的而言,总是有一个表达式,而不是原始设计中的声明.
在C#3中,根本没有办法表达一个表达式树,它的主体是一个空语句块.最近,表达式树库已经扩展到允许语句,但C#语义分析规则没有更新以利用它; 你仍然无法将语句lambda转换为表达式树.
事实证明,使用Expression.Lambda(). 然而,我仍然对可能的其他答案感兴趣。
我确实需要一个我之前编写的辅助方法:
/// <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 );
}
Run Code Online (Sandbox Code Playgroud)
完成后,EventInfo您可以为其创建一个空的 lambda,如下所示:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1590 次 |
| 最近记录: |