简体   繁体   English

将委托作为方法参数传递

[英]Passing delegate as method parameter

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. 我目前正在开发一个EventManager类,以确保没有事件连接到死WCF双工客户端,并且还控制防止从同一客户端到一个事件的多个连线。

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);

To call this: 称之为:

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)
}

Update 更新

The code for SomeEventDelegate wrapper is: SomeEventDelegate包装器的代码是:

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

event SomeEventHandler SomeEvent;

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. 显然代理没有被返回到myObject.SomeEventDelegate并且我无法从方法返回Delegate,因为我之后也需要一些验证。 Do you have any idea on how to do this? 你对如何做到这一点有任何想法吗?

Use the C# ref parameter modifier : 使用C# ref参数修饰符

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)
}

Note also that there exists some nice syntactic sugar (as of C# 2.0) for assigning and combining delegates (see this article , for example): 还要注意,存在一些很好的语法糖(从C#2.0开始)用于分配和组合代理(例如,参见本文 ):

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)
}

It has been pointed out to me that ref only works with fields, not properties. 有人向我指出, ref只适用于字段,而不适用于属性。 In the case of a property, an intermediary variable can be used: 在属性的情况下,可以使用中间变量:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM