如何从不同类中的另一个回调方法执行抽象类中的异步方法

我有一个名为 AncSubscriberWrapper 的具体类,它有一个回调方法


    public Task OnUnshownCounterUpdatedAsync(long counter)

    {

        return Task.CompletedTask;

    }

而且我有一个抽象类调用 BasePageViewModel 它有一个异步方法


    protected async void GetUnseenNotificationsCount()

    {

        UnseenNotificationCount  = await m_ancSubscriberWrapper.TryGetNotificationCountAsync(NotificationStatus.Delivered | NotificationStatus.Created);

    }

类路径在项目内部如下所示。


./src/Visit.Common/Services/AncSubscriberWrapper.cs ./src/Visit.Common/ViewModels/PageViewModels/BasePageViewModel.cs


我需要的是从 OnUnshownCounterUpdatedAsync() 方法执行 GetUnseenNotificationsCount() 方法。


我怎样才能做到这一点?


元芳怎么了
浏览 165回答 1
1回答

哔哔one

这是我能够实现目标的一种方式。我不确定这是不是这样做的正确方法。我如何实现我的目标是使用 EventHandler。为 AncSubscriberWrapper 类创建一个接口(IAncSubscriberWrapper)public interface IAncSubscriberWrapper{&nbsp; &nbsp; event EventHandler UnshownNotificationCounterUpdated;}并像下面那样实现它public class AncSubscriberWrapper : NotificationCenterFacade, IAncSubscriberWrapper然后实现AncSubscriberWrapper类里面的接口成员public event EventHandler UnshownNotificationCounterUpdated;并在 OnUnshownCounterUpdatedAsync 方法中调用方法public Task OnUnshownCounterUpdatedAsync(long counter){&nbsp; &nbsp; UnshownNotificationCounterUpdated?.Invoke(this, null);&nbsp; &nbsp; return Task.CompletedTask;}然后去 BasePageViewModel 注册和注销监听器。public void Initialize(){&nbsp; &nbsp; m_ancSubscriberWrapper.UnshownNotificationCounterUpdated += OnUnshownNotificationCounterUpdated;}public void Teardown(){&nbsp; &nbsp; m_ancSubscriberWrapper.UnshownNotificationCounterUpdated -= OnUnshownNotificationCounterUpdated;}由于 BasePageViewModel 是一个抽象类,任何使用它的具体类都会覆盖这些方法。(下面的代码片段与这个问题没有直接关系,而是为了理解我的代码基础上的设计)/** BaseContainerViewController is only accepting TPageViewModel generic type of classes only.* TPageViewModel inherits BasePageViewModel and BaseContainerViewController inherits BaseViewController* That's what following line is all about*/public abstract class BaseContainerViewController<TPageViewModel> : BaseViewController where TPageViewModel : BasePageViewModel和public class WardListViewController : BaseContainerViewController<WardListPageViewModel>回到答案的最后一部分。在 BasePageViewModel 类中添加以下方法,这将完成该过程。protected virtual void OnUnshownNotificationCounterUpdated(object sender, EventArgs eventArgs)&nbsp;{&nbsp; &nbsp; GetUnseenNotificationsCount();}
打开App,查看更多内容
随时随地看视频慕课网APP