简体   繁体   中英

Subscribing and unsubscribing from a method instead of a delegate?

I know there are times you need to keep track of a delegate so that it can be unsubscribed properly:

private EventHandler _handler;

public void Foo()
{
    if (_handler != null)
    {
        Something.SomeEvent -= _handler; // Unsubscribe old event
    }

    _handler = delegate(object sender, EventArgs args) { };;
    Something.SomeEvent += _handler;
}

But, is that still necessary if you use a method instead?

public void CustomMethod(object sender, EventArgs args) { ... }

public void Foo()
{
    // Not sure how to unsubscribe only if it wasn't subscribed first?
    if (some way to check)
    {
        Something.SomeEvent -= CustomMethod;
    }

    Something.SomeEvent += CustomMethod;
}

No, it's not necessary. If you are always subscribing/unsubscribing the same method (in the form of a delegate), then you don't need to track the actual delegate instance that was subscribed. The new delegate instances (implicitly created for you by the C# compiler in the += and -= operations) are correctly identified as identical, so that the -= operation removes the delegate that was added in the += operation.

In other words, equality for the Delegate class is not just "reference equality". Two completely different Delegate instances that have the same invocation list are considered equal.

If you wanna check if a specific method subscribed or not you can use GetInvocationList and then Linq:

var mInfo = typeof(SomeType).GetMethod("CustomMethod");

if(Something.SomeEvent.GetInvocationList().Any(x => x.Method == mInfo))
{

}

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