2010-04-14 11 views
0

Ive는 배우려고하는 대의원들과 놀았으며 한 가지 작은 문제를 만났습니다.대리자를 사용하여 목록 상자 채우기

class myClass 
{ 
    OtherClass otherClass = new OtherClass(); // Needs Parameter 
    otherClass.SendSomeText(myString); 
} 

class OtherClass 
{ 
    public delegate void TextToBox(string s); 

    TextToBox textToBox; 

    public OtherClass(TextToBox ttb) // ***Problem*** 
    { 
     textToBox = ttb; 
    } 

    public void SendSomeText(string foo) 
    { 
     textToBox(foo); 
    } 
} 

형태 다음 OtherClass 생성자 매개 변수로 TextToBox을 찾고 있기 때문에

public partial class MainForm : Form 
    { 
    OtherClass otherClass; 

    public MainForm() 
    { 
     InitializeComponent(); 
     otherClass = new OtherClass(this.TextToBox); 
    } 

    public void TextToBox(string aString) 
    { 
     listBox1.Items.Add(aString); 
    } 

} 

은 분명히이 나던 컴파일합니다. 폼의 텍스트 상자에 myClass의 객체를 가져올 수 있도록 문제를 해결하는 것이 좋습니다.

답변

2

당신은

class OtherClass 
{ 
    public delegate void TextToBox(string s); 

    TextToBox textToBox; 

    public OtherClass() 
    { 
    } 
    public OtherClass(TextToBox ttb) // ***Problem*** 
    { 
     textToBox = ttb; 
    } 

    public void SendSomeText(string foo) 
    { 
     if (textToBox != null) 
      textToBox(foo); 
    } 
} 

처럼 뭔가에 OtherClass을 변경할 수 있습니다하지만 난 당신이 정말 myClass가 넘는 많은 제어를 해달라고

class myClass 
{ 
    OtherClass otherClass = new OtherClass(); // Needs Parameter 
    otherClass.SendSomeText(myString); 
} 
+1

으로 실현하려 할 무엇을 아주 확실하지 않다. API를 통해 수신되는 스트림입니다. 내가 왜 다른 생성자를 추가하지 않았는지 확실하지 않습니다. –

관련 문제