Using WeakEventManager, hiding the actual event

岁酱吖の 提交于 2021-02-11 14:27:54

问题


When using the WeakEventManager, it is apparent that the event is hooked up to the AddHandler using reflection (from nameof() in example). The AddHandler does NOT work if the event is private or protected. I'd prefer to not expose the event and force the consumers to use the Subscribe events. I could use a private class to hold the events.

 public static event EventHandler<IntensityChangedEventArgs> OnIntensityChanged;

    public static void Subscribe_OnIntensityChanged(EventHandler<IntensityChangedEventArgs> eventHandler)
    {
        WeakEventManager<ADAHelper, IntensityChangedEventArgs>.AddHandler(instance, nameof(ADAHelper.OnIntensityChanged), eventHandler);
    }

This works but the problem is that the

public static event EventHandler<IntensityChangedEventArgs> OnIntensityChanged; is public exposed. This needs to be private so that consumers of the event can't subscribe to it directl (which causes the problem this fixes) I want to force them to Subscribe_OnIntensityChanged method.

A one-off private class would work, a re-usable generic would be great.

How do I create a wrapper class (for the event) to hide the event from public (or internal) usage?


回答1:


I implemented a private class. I did try the generic route for a bit but the syntax and clarity of the solution was less than ideal. Private class is probably better as you only need one private class that could then hold many events.

 /// <summary>
    /// wrapper to keep from exposing the actual event. Want to force them to subscribe weakly
    /// </summary>
    private OnIntensityChangedEventWrapper onIntensityChangedEventWrapper = new ADAHelper.OnIntensityChangedEventWrapper();

    /// <summary>
    /// Event notifying when the intensity has changed. This event will only fire when the ADA button was pressed.
    /// </summary>
    public static void Subscribe_OnIntensityChanged(EventHandler<IntensityChangedEventArgs> eventHandler)
    {
        WeakEventManager<OnIntensityChangedEventWrapper, IntensityChangedEventArgs>.AddHandler(Instance.onIntensityChangedEventWrapper, nameof(OnIntensityChangedEventWrapper.OnIntensityChanged), eventHandler);
    }

    private class OnIntensityChangedEventWrapper
    {
        public event EventHandler<IntensityChangedEventArgs> OnIntensityChanged;

        public void Fire(Intensity intensity)
        {
            if (OnIntensityChanged != null)
            {
                OnIntensityChanged(this, new IntensityChangedEventArgs(intensity));
            }
        }
    }


来源:https://stackoverflow.com/questions/34030047/using-weakeventmanager-hiding-the-actual-event

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