2011-03-23 3 views
0

OO에 완전히 익숙하므로 친절하십시오.두 가지 방법으로 StreamReader를 참조하십시오.

나는 button1을 클릭 할 때 파일 대화 상자를 열고 내용을 스트림 리더 sr로 읽는 메서드를 만들었습니다.

public void button1_Click(object sender, EventArgs e) 
    { 
     if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      label1.Text = openFileDialog1.FileName; 

      StreamReader sr = new StreamReader(label1.Text); 
      String strNumVertices = sr.ReadLine(); 
      label2.Text = strNumVertices; 
     } 
    } 

다른 코드는 Form1_Paint 메서드에서 실행됩니다.

public void Form1_Paint(object sender, PaintEventArgs e) 

     perspectiveMatrix = new Gmatrix("perspective"); 
     translationMatrix = new Gmatrix("translation"); 
     scalingMatrix = new Gmatrix("scaling"); 

     perspectiveMatrix.initAsPerspectiveMatrix(300); 

     scalingMatrix.initAsScalingMatrix(10, 10, 10); 

     translationMatrix.initAsTranslationMatrix(150, 50, 1200); 

     String strNumVertices = sr.ReadLine(); 
     label1.Text = strNumVertices; 

제 질문은, 어떻게 스트림 리더 sr을 Form1_paint 메서드의 button1_click 메서드에서 참조합니까?

답변

4

조언을 구하십시오. 시도하지 마십시오.

이렇게하면 파일이나 스트림을 열어 볼 위험이 있습니다.

각 방법마다 새 스팀 판독기를 열거 나 자체 메서드로 추출하는 것이 좋습니다.

참고 :

당신은 적절한 처분을 보장하기 위해 using 문에서 스트림의 오프닝을 포장해야

:

using(StreamReader sr = new StreamReader(label1.Text)) 
{ 
    String strNumVertices = sr.ReadLine(); 
    label2.Text = strNumVertices; 
} 
0

왜 당신이 파일에서 읽은 데이터를 저장하지 및 파일을 다시 읽지 않고 다시 사용 하시겠습니까? 나는이 메소드들이 같은 클래스 (그리고 객체의 동일한 인스턴스)에 있다고 가정하고 있지만, 그렇지 않은 경우에는 주위에 방법이있다.

private string StrNumVertices { get; set; } 


public void button1_Click(object sender, EventArgs e) 
{ 
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 
     label1.Text = openFileDialog1.FileName; 

     StreamReader sr = new StreamReader(label1.Text); 
     this.StrNumVertices = sr.ReadLine(); 
     label2.Text = this.StrNumVertices; 
    } 
} 

public void Form1_Paint(object sender, PaintEventArgs e) 

    perspectiveMatrix = new Gmatrix("perspective"); 
    translationMatrix = new Gmatrix("translation"); 
    scalingMatrix = new Gmatrix("scaling"); 

    perspectiveMatrix.initAsPerspectiveMatrix(300); 

    scalingMatrix.initAsScalingMatrix(10, 10, 10); 

    translationMatrix.initAsTranslationMatrix(150, 50, 1200); 

    label1.Text = this.StrNumVertices; 

    ... 
} 

는 개체의 동일한 인스턴스 아니라면, 그때는 싱글 구성 객체 (또는 캐시)를 사용하고 거기에 데이터를 저장하는 생각 하는데요. 물론 이것은 데이터의 범위와 수명에 달려 있습니다. 전체 응용 프로그램 또는이 인스턴스에만 적용됩니까? 가장 좋은 방법은 위와 같은 인스턴스 속성으로 만드는 것입니다. 객체가 다시 생성되면 다른 기법을 사용해야합니다.

파일을 다시 읽으려면 다른 행의 데이터이기 때문에 스트림을 다시 사용하거나 한 번에 모든 데이터를 읽을 필요가 있습니다 (가능한 경우). 그런 다음 내부적으로 읽은 항목을 반복합니다.

0

양식 클래스의 필드로 지정하십시오. 이렇게하면 메서드에서 전체 양식으로 범위가 변경됩니다. 이전 게시물의 경고는 여전히 유효합니다.

StreamReader sr; 
public void button1_Click(object sender, EventArgs e) 
{ 
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
    { 
     label1.Text = openFileDialog1.FileName; 

     sr = new StreamReader(label1.Text); 
     String strNumVertices = sr.ReadLine(); 
     label2.Text = strNumVertices; 
    } 
} 

public void Form1_Paint(object sender, PaintEventArgs e) 

    perspectiveMatrix = new Gmatrix("perspective"); 
    translationMatrix = new Gmatrix("translation"); 
    scalingMatrix = new Gmatrix("scaling"); 

    perspectiveMatrix.initAsPerspectiveMatrix(300); 

    scalingMatrix.initAsScalingMatrix(10, 10, 10); 

    translationMatrix.initAsTranslationMatrix(150, 50, 1200); 

    if (sr != null) { 
     String strNumVertices = sr.ReadLine(); 
     label1.Text = strNumVertices; 
    } 
+0

이 질문에 대답하지만, 나는이 접근법에 의문을 제기합니다. 1. 모든 페인트에서 열린 스트림 2.ReadLine()을 유지하는 것이 매우 느릴 것입니다 3.파일이 끝날 때 –

+0

응답을 보내 주셔서 감사합니다 답장을 주셔서 감사합니다 ... – Gary

+0

당신이 제안한 솔루션을 나타내는 반면 제안 된 코드는 label1에 Form1_Paint 메서드의 strNumVertices 값을 채우지 않습니다 왜 이래요? – Gary

1

사실 실제로는 페인트를 실행할 때마다 스트림에서 읽지 않는 것이 좋습니다. 아마도 값을 한 번 읽고 폼의 멤버 변수에 저장하고 페인트 메서드에 액세스하고 싶습니까?

+1

하하, 내 상사가 채팅을하기 위해 나왔으므로 펀치로 나를 때렸다. 당신은 충분한 담당자가 있고, 계속하고, 대답을 삭제하고, qudos를 갖도록하십시오. ;) – BenCr

+0

@BenCr : 나는 대신 당신의 것을 upvoted했습니다. 어쨌든 우리는 기본적으로 같은 것을 씁니다 :) – Vlad

1

버튼 클릭과 페인트 메소드가 호출되는 사이에 파일이 변경 될 것으로 예상되는 경우가 아니라면 어쨌든 파일을 다시 읽지 않아야합니다.

파일을 읽는 것은 결과를 필드에 저장하고 페인트 방법 중에 다시 가져 오는 것과 비교할 때 성능 측면에서 매우 비쌉니다. 또는 첫 번째 실행에 따라 그 반대 일 수 있습니다.

관련 문제