简体   繁体   中英

Avoid attaching event again

情况是这样的,我有一个控件,并且它在控件的定义中具有事件Render,对此事件附加了处理程序,我正在寻找一种方法来显示某种消息,如果在使用此控件的某个类中另一个处理程序是与此事件相关的最佳问候,Iordan

dont expose the event publicly. expose it as a property. this will give you control when external classes are attaching handlers

class MyClass { private EventHandler _myEvent;

public event EventHandler MyEvent
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add 
    { 
        _myEvent = (EventHandler)Delegate.Combine(_myEvent, value);
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove 
    { 
        _myEvent = (EventHandler)Delegate.Remove(_myEvent, value); 
    }
}
...

}

more info on this here

http://msdn.microsoft.com/en-us/magazine/cc163533.aspx

I'm confused.

Can you detect the calling of '+= new EventHandler ( ... )' and stop it ... what?

I think you just need to organise your code better. Or re-word your question.

This does not strike me as a good approach. When using events, the control should typically not be dependent on the number of event handlers attached. It should work regardless of whether there are 0 or 27 event handlers reacting on the event. If you want to have a mechanism where you have more control you should probably consider using a delegate instead.

If you for some reason are restricted to use the event model and want to have control over the assignment of event handlers, one approach might be to inherit the original class, creating an event in that class with the same name and signature as in the base class (using the new keyword so that the original event is hidden), and keep track of how event handlers are attached and detached:

public class BaseClass
{
    public event EventHandler SomeEvent;
}

public class MyClass : BaseClass
{
    private int _refCount = 0;
    public new event EventHandler SomeEvent
    {
        add
        {
            if (_refCount > 0)
            {
                // handler already attached
            }
            base.SomeEvent += value;
            _refCount++;
        }
        remove
        {
            base.SomeEvent -= value;
            _refCount--;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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