gpt4 book ai didi

c# - 向接口(interface)/实现添加事件

转载 作者:太空宇宙 更新时间:2023-11-03 20:42:34 25 4
gpt4 key购买 nike

知道之前有人问过这个问题,但我的问题略有不同。

我有一个界面:

IEmailDispatcher

看起来像这样:

public interface IEmailDispatcher
{
void SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary<string, byte[]> Attachments);
}

作为一点背景:

我有一个具有以下方法的静态 EmailDispatcher 类: SendEmail(string[] to, string fromName, string fromAddress, string subject, string body, bool bodyIsHTML, Dictionary Attachments);

这通过 IoC,然后加载相关的 IEmailDispatcher 实现,并调用该方法。

然后我的应用程序可以简单地调用 EmailDispatcher.SendEmail(.........

我想向其中添加事件,例如 OnEmailSent、OnEmailFail 等...这样每个实现都可以处理发送电子邮件的成功和失败,并相应地记录它们。

我该怎么做?

或者,有没有更好的办法?

目前,我正在使用基本上使用 System.Net 命名空间的“BasicEmailDispatcher”,创建 MailMessage 并发送它。

在未来,我将创建另一个类,以不同方式处理邮件...将其添加到 sql db 表以进行报告等...因此将以与 BasicEmailDispatcher 不同的方式处理 OnEmailSent 事件

最佳答案

看起来试图将所有内容都放入静态类会让你在这里做一些尴尬的事情(具体来说,使用静态类实现 the template pattern)。如果调用方(应用程序)只需要了解 SendEmail 方法,那么接口(interface)中应该只包含该方法。

如果确实如此,您可以让您的基本调度程序类实现模板模式:

public class EmailDispatcherBase: IEmailDispatcher {
// cheating on the arguments here to save space
public void SendEmail(object[] args) {
try {
// basic implementation here
this.OnEmailSent();
}
catch {
this.OnEmailFailed();
throw;
}
}
protected virtual void OnEmailSent() {}
protected virtual void OnEmailFailed() {}
}

更复杂的实现将各自继承自 BasicEmailDispatcher(因此实现 IEmailDispatcher)并覆盖一个或两个虚拟方法以提供成功或失败行为:

public class EmailDispatcherWithLogging: EmailDispatcherBase {
protected override OnEmailFailed() {
// Write a failure log entry to the database
}
}

关于c# - 向接口(interface)/实现添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1975922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com