传递代理作为方法参数 [英] Passing delegate as method parameter

查看:172
本文介绍了传递代理作为方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个EventManager类,以确保没有事件被连接到死亡的WCF双工客户端,并且还可以控制防止同一客户端进行多个接线到一个事件。

I'm currently developing an EventManager class to ensure that no events are left wired to dead WCF duplex clients, and also to control prevent multiple wiring from the same client to the one event.

现在基本上,我正在试图将事件委托传递给一个可以控制这样的赋值的函数。

Now basically, I'm what stuck with is trying to pass the event delegate to a function that will control the assignment like this.

var handler = new SomeEventHandler(MyHandler);
Wire(myObject.SomeEventDelegate, handler);

要调用:

private void Wire(Delegate eventDelegate, Delegate handler)
{
    // Pre validate the subscription.
    eventDelegate = Delegate.Combine(eventDelegate, handler);
    // Post actions (storing subscribed event delegates in a list)
}

更新

SomeEventDelegate包装器的代码是:

The code for SomeEventDelegate wrapper is:

public Delegate SomeEventDelegate
{
    get { return SomeEvent; }
    set { SomeEvent = (SomeEventHandler) value; }
}

event SomeEventHandler SomeEvent;

显然,委托没有被返回到myObject.SomeEventDelegate
我不能返回由于我也需要一些验证,因此该方法的代理。
你有什么想法吗?

Obviously the delegate is not being returned to the myObject.SomeEventDelegate And I cannot return the Delegate from the method because I need some validation after too. Do you have any idea on how to do this?

推荐答案

使用 C# ref 参数修饰符

Use the C# ref parameter modifier:

var handler = new SomeEventHandler(MyHandler);
Wire(ref myObject.SomeEventDelegate, handler);

private void Wire(ref Delegate eventDelegate, Delegate handler)
{
    // Pre validate the subscription.
    eventDelegate = Delegate.Combine(eventDelegate, handler);
    // Post actions (storing subscribed event handlers in a list)
}

还要注意,存在一些很好的语法糖(C#2.0),用于分配和组合代理(参见这篇文章,例如)

Note also that there exists some nice syntactic sugar (as of C# 2.0) for assigning and combining delegates (see this article, for example):

Wire(ref myObject.SomeEventDelegate, MyHandler);

private void Wire(ref Delegate eventDelegate, Delegate handler)
{
    // Pre validate the subscription.
    eventDelegate += handler;
    // Post actions (storing subscribed event handlers in a list)
}

已经指出, ref 仅适用于字段而不是属性。在属性的情况下,可以使用中间变量:

It has been pointed out to me that ref only works with fields, not properties. In the case of a property, an intermediary variable can be used:

var tempDelegate = myObject.SomeEventDelegate;
Wire(ref tempDelegate, MyHandler);
myObject.SomeEventDelegate = tempDelegate;

这篇关于传递代理作为方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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