C#实现接口

时间:2019-07-09 14:18:23

标签: c# design-patterns

如果可能,我想实现接口,但我自己不能实现。

我有两种方法:

    public async Task<ActionResult> Send([FromBody] EmailDto email)
    {
        //send email
    }

    public async Task<ActionResult> SendMany([FromBody] EmailManyDto email)
    {
        //send email
    }

我有两个班级:

public class EmailDto 
{
    public string Recipient { get; set; }
    public string Content { get; set; }
    public string Subject { get; set; }
}

public class EmailManyDto
{
    public List<string> Recipients { get; set; }
    public string Content { get; set; }
    public string Subject { get; set; }
}

我想将这两个端点合并为一个端点。 我认为我应该尽可能实现最通用的接口-IEnumerable来接收收件人。

一般来说,我需要重构此代码。

1 个答案:

答案 0 :(得分:1)

您可以创建一个接受一个或多个电子邮件地址的DTO:

public class EmailManyDto
{
    public string Recipient 
    {
        get
        {
            return Recipients.FirstOrDefault();
        }
        set
        {
            Recipients.Insert(0, value);
        }
    }
    public List<string> Recipients { get; set; } = new List<string>();
    public string Content { get; set; }
    public string Subject { get; set; }
}

这样,您的旧客户端将继续工作,并且您可以将代码重构为一种方法。

通过将单个收件人存储在列表的开头,您可以统一代码:

public async Task<ActionResult> SendMany([FromBody] EmailManyDto email)
{
    foreach (var recipient in email.Recipients)
    {
        // send your mail
    }
}
相关问题