添加多个元素的流畅界面问题

时间:2017-10-09 19:37:16

标签: c# fluent

我有以下代码(来自mailgun_csharp):

var message = new MessageBuilder()
            .SetSubject(Subject)
            .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
            .SetHtmlBody(Body)
            .AddToRecipient(new Recipient { Email = "a@a.com", DisplayName = "a" })
            .GetMessage();
到目前为止,非常好......

现在我想添加2个收件人:

var message = new MessageBuilder()
            .SetSubject(Subject)
            .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
            .SetHtmlBody(Body)
            .AddToRecipient(new Recipient { Email = "a@a.com", DisplayName = "a" })
            .AddToRecipient(new Recipient { Email = "b@a.com", DisplayName = "b" })
            .GetMessage();

这也很有效......

但如果我有一个List并且我想将整个列表添加到.AddRecipient,我该如何以编程方式执行此操作?

2 个答案:

答案 0 :(得分:2)

看起来mailgun_csharp库缺少一种将收件人列表传递给API的方法。 C#允许您通过添加自己的实现作为扩展来解决这个缺点:

public static class MessageBuilderExtensions {
    public static IMessageBuilder AddToRecipients(
        this IMessageBuilder builder
    ,   IEnumerable<IRecipient> recipients
    ,   JObject recipientVariables = null) {
        foreach (var recipient in recipients) {
            builder = builder.AddRecipient(recipient, recipientVariables);
        }
        return builder;
    }
}

现在你可以写下这段代码:

IEnumerable<IRecipient> myListOfRecipients = ...
var message = new MessageBuilder()
    .SetSubject(Subject)
    .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
    .SetHtmlBody(Body)
    .AddToRecipients(myListOfRecipients)
    .GetMessage();

答案 1 :(得分:0)

您可以使用Aggregate中的System.Linq

var messageBuilder = new MessageBuilder()
        .SetSubject(Subject)
        .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
        .SetHtmlBody(Body);

var message = recipients.Aggregate(messageBuilder,
    (builder, recipient) => builder.AddToRecipient(recipient),
    builder => builder.GetMessage());