public class LivetWeakEventListener<TDelegate, TEventArgs> where TEventArgs : EventArgs
{
private EventHandler<TEventArgs> _handler;
private TDelegate _resultHandler;
private Action<TDelegate> _remove;
private static void ReceiveEvent(WeakReference listenerWeakReference, object sender, TEventArgs args)
{
var listener = listenerWeakReference.Target as LivetWeakEventListener<TDelegate, TEventArgs>;
if (listener != null)
{
var handler = listener._handler;
if (handler != null)
{
handler(sender, args);
}
}
}
private static TDelegate GetStaticHandler(WeakReference listenerWeakReference, Func<EventHandler<TEventArgs>, TDelegate> conversion)
{
return conversion((sender, e) => ReceiveEvent(listenerWeakReference, sender, e));
}
private LivetWeakEventListener() { }
//コンストラクタ
public LivetWeakEventListener(
Func<EventHandler<TEventArgs>, TDelegate> conversion,
Action<TDelegate> add,
EventHandler<TEventArgs> handler)
{
_handler = handler;
_resultHandler = GetStaticHandler(new WeakReference(this), conversion);
add(_resultHandler);
}
//解放
public void Release()
{
_remove(_resultHandler);
}
}
ICAgIHB1YmxpYyBjbGFzcyBMaXZldFdlYWtFdmVudExpc3RlbmVyPFREZWxlZ2F0ZSwgVEV2ZW50QXJncz4gd2hlcmUgVEV2ZW50QXJncyA6IEV2ZW50QXJncwogICAgewogICAgICAgIHByaXZhdGUgRXZlbnRIYW5kbGVyPFRFdmVudEFyZ3M+IF9oYW5kbGVyOwogICAgICAgIHByaXZhdGUgVERlbGVnYXRlIF9yZXN1bHRIYW5kbGVyOwogICAgICAgIHByaXZhdGUgQWN0aW9uPFREZWxlZ2F0ZT4gX3JlbW92ZTsKCiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgdm9pZCBSZWNlaXZlRXZlbnQoV2Vha1JlZmVyZW5jZSBsaXN0ZW5lcldlYWtSZWZlcmVuY2UsIG9iamVjdCBzZW5kZXIsIFRFdmVudEFyZ3MgYXJncykKICAgICAgICB7CiAgICAgICAgICAgIHZhciBsaXN0ZW5lciA9IGxpc3RlbmVyV2Vha1JlZmVyZW5jZS5UYXJnZXQgYXMgTGl2ZXRXZWFr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