2013-05-28 228 views
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(); 
    } 
+0

你的第二句话对我来说完全不清楚。如果你在一起讨论链接构造函数,请参阅http://stackoverflow.com/questions/985280/can-i-call-a-overloaded-constructor-from-another-constructor-of-the-same-class-i ?rq = 1 –

+0

这正是我想要的,谢谢乔恩!对不起,缺少咖啡。 –

回答

1

您可以使用下面的语法来调用另一个构造,它是一个净功能:

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(); 
} 
2

作为替代构造器链接:

如果你想要的所有构造函数初始化clientmessage您应该将初始化从默认构造函数移动到定义私有字段的位置,如下所示:

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

这样你就可以保证它们会被你碰巧写的任何构造函数初始化。我认为你也可以让他们只读。

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

类似的字段按照它们出现在类定义中的顺序进行初始化(显然这对于​​知道非常重要)。