Note that there are some explanatory texts on larger screens.

plurals
  1. POUnsubscribe from delegate passed through ref keyword to the subscription method?
    text
    copied!<p>I've got the following class:</p> <pre><code>public class Terminal : IDisposable { readonly List&lt;IListener&gt; _listeners; public Terminal(IEnumerable&lt;IListener&gt; listeners) { _listeners = new List&lt;IListener&gt;(listeners); } public void Subscribe(ref Action&lt;string&gt; source) { source += Broadcast; //Store the reference somehow? } void Broadcast(string message) { foreach (var listener in _listeners) listener.Listen(message); } public void Dispose() { //Unsubscribe from all the stored sources? } } </code></pre> <p>I've searched for a while and it appears that an argument passed with the ref keyword can't be stored. Trying to add the source argument to a list or to assign it to a field variable doesn't allow it to keep a reference to the actual delegate's original reference; so my questions are:</p> <ul> <li>Is there a way to unsubscribe from all the sources without passing their references again?</li> <li>If not, how can the class be changed in order to support it, but still maintain the subscription by passing a delegate through a method?</li> <li>Is it possible to achieve it without using Reflection?</li> <li>Is it possible to achieve it without wrapping the delegate/event in a class and then passing the class as a parameter for the subscription?</li> </ul> <p>Thank you.</p> <p><strong>EDIT:</strong> It appears that without using a Wrapper or Reflection, there's no solution to the given problem. My intention was to make the class as much portable as possible, without having to wrap delegates in helper classes. Thanks everyone for the contributions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload