Passing delegate as method parameter

≡放荡痞女 提交于 2019-12-23 09:29:08

问题


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

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:

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. Do you have any idea on how to do this?


回答1:


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

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

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;


来源:https://stackoverflow.com/questions/3938356/passing-delegate-as-method-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!