1

我如何在公共中调用私人构造函数?我想从 setter 和 setter 调用对象初始化程序公开调用。

    private MyMailer() // objects initializer
    {
        client = new SmtpClient(SMTPServer);
        message = new MailMessage {IsBodyHtml = true};
    }

    private MyMailer(string from) //from setter
    {
        SetFrom(from);
    }

    public MyMailer(string from, string to, string cc, string bcc, string subject, string content)
    {
        foreach (string chunk in to.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries))
        {
            AddTo(chunk);    
        }

        foreach (string chunk in cc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
        {
            AddCC(chunk);
        }

        foreach (string chunk in bcc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
        {
            AddBCC(chunk);
        }
        SetSubject(subject);
        SetMessage(content);
        Send();
    }
4

2 回答 2

2

作为构造函数链接的替代方案:

如果您希望所有构造函数初始化client,并且message应该将初始化从默认构造函数移动到定义私有字段的位置,如下所示:

private readonly SmtpClient client = new SmtpClient(SMTPServer);
private readonly MailMessage message = new MailMessage {IsBodyHtml = true};

这样,您就可以保证它们将由您碰巧编写的任何构造函数初始化。我认为您也可以将它们设为只读。

注意:只有SMTPServer在构造时初始化才有效,例如,如果它是一个返回不依赖于其他字段的值的属性。否则,您可能需要为其使用另一个字段,该字段像其他两个字段一样同时声明和初始化。

像这样的字段按照它们在类定义中出现的顺序进行初始化(这显然很重要)。

于 2013-05-28T09:45:15.670 回答
1

您可以使用以下语法调用另一个构造函数,它是一个 .Net 功能:

private MyMailer() // objects initializer
{
    client = new SmtpClient(SMTPServer);
    message = new MailMessage {IsBodyHtml = true};
}

private MyMailer(string from) //from setter
    : this() // calls MyMailer()
{
    SetFrom(from);
}

public MyMailer(string from, string to, string cc, string bcc, string subject, string content)
    : this(from) // calls MyMailer(from)
{
    foreach (string chunk in to.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries))
    {
        AddTo(chunk);    
    }

    foreach (string chunk in cc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
    {
        AddCC(chunk);
    }

    foreach (string chunk in bcc.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
    {
        AddBCC(chunk);
    }
    SetSubject(subject);
    SetMessage(content);
    Send();
}
于 2013-05-28T09:41:14.783 回答