2013-05-28 3 views
1

어떻게 public constructor를 public으로 호출 할 수 있습니까? setter와 setter invoke 객체 이니셜 라이저에서 공개적으로 호출하고 싶습니다.중첩 된 개인 생성자 호출

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

두 번째 문장은 나에게 완전히 불분명합니다. 연결 생성자를 함께 연결하는 방법에 대해서는 http://stackoverflow.com/questions/985280/can-i-call-a-overloaded-constructor-from-another-constructor-of-the-ameame-classi-i를 참조하십시오. ? rq = 1 –

+0

정확히 내가 원했던 것입니다. Jon에게 감사드립니다! 미안, 커피 부족. –

답변

1

당신은 다른 생성자를 호출하려면 다음 구문을 사용할 수 있습니다, 그것은 닷넷 기능입니다 clientmessage 초기화 연산자를 기본 생성자에서 비공개 필드가 정의 된 지점으로 이동해야합니다 (예 :

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

그런 식으로 작성자가 생성자에 의해 초기화된다는 것을 보장 할 수 있습니다. 나는 당신이 아마 그것들을 읽기 전용으로 만들 수 있다고 생각한다.

참고 : 구성 시간에 SMTPServer이 초기화 된 경우에만 작동합니다 (예 : 다른 필드에 종속되지 않는 값을 반환하는 속성 인 경우). 그렇지 않으면 다른 두 필드와 같이 동시에 선언되고 초기화되는 다른 필드를 사용해야 할 수도 있습니다.

필드는 클래스 정의에 나타나는 순서대로 초기화됩니다 (분명히 알고 있어야 함).

2

체인 생성자의 대안으로 :

당신은 모든 생성자 초기화하려면

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