2009-12-22 2 views
0

저는 C#에서 극단적 인 초보자입니다. 그러나 헤드 스타트 ​​C# 튜토리얼 북을 천천히 살펴 보았습니다. 그러나 첫 번째 "실험실"과제에서 벽에 부딪혔습니다. PictureBox를 제어하는 ​​코드를 제공하고 기본 폼에서 작동하도록 코드를 가져올 수는 있지만 클래스 내에서 작동하도록 할 수는 없습니다. . 나는 이전 레슨을 마치고 돌아 왔고, 나는 실종 된 것에 대해 상당히 좋은 생각을 가지고있다. 그러나 내 인생에서 나는 내 수업 내에서 메인 폼의 PictureBox에 액세스하는 방법을 알아낼 수 없다. 튜토리얼에서 나에게해야한다고 말하고 있기 때문에).C# Newbie 튜토리얼 북에서 질문 : "헤드 스타트 ​​C# 그레이하운드 랩"

나는이 책에서 전혀 뛰어 들지 않았기 때문에 조금 실망 스럽지만, 아직 우리가 이것을 다루지 않았다고 맹세하겠다. 어쨌든, 진짜 프로그래머들에게 호소력이 있습니다.

자습서의 코드 "코드를 사용하여 개체가 양식에서 제어 할 수 있습니다"(책이있는 모든 사용자를위한 p208)입니다.

Point p = MyPictureBox.Location 
p.x += distance; 
MyPictureBox.Location = p 

아래에서 관련 코드를 게시 할 예정입니다. 아래 코드를 사용하십시오. Button1은 컴파일 할 때 작동합니다. Button2는 "작동합니다"라는 의미에서 현재 클래스는 전달 된 INT를 인쇄하도록 지시합니다. 왜냐하면 내가 작동하지 못하는 코드를 주석 처리했기 때문입니다.

미리 감사드립니다. Form1에 대한

코드 : PicMover 클래스

// 


using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
// Namespaces I'll need. 

namespace Troubleshooting_PicBoxes 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); // Start all the Form1 stuff (all IDE-generated) 

    } 

    private void button1_Click(object sender, EventArgs e) //method from clicking the first button 
    { 
     int distance = 5; // Create this variable called "distance" 

     Point BoxMovement = MyPictureBox.Location; //create a point called BoxMovement 

     BoxMovement.X += distance; // Adjust the X of BoxMovement by my distance int. 

     MyPictureBox.Location = BoxMovement; // now adjust the Box by the Point's location. 

    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     PicMover PicMoverObject1 = new PicMover(); // Reserve Space for&Create object 
     PicMoverObject1.MoveThatPic(5); // Execute Object Method with a value of 5 




    } 


} 
} 

코드 : 당신이 뭔가에 액세스해야하는 경우

// 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace Troubleshooting_PicBoxes 
{ 
class PicMover 
{ 


    public void MoveThatPic(int distance) // New method, 
              // takes a variable called Distance. 

    { 
     MessageBox.Show(distance.ToString()); // Just show us that Variable. 


     // I need to be able to access Form1's picture box before I can use this. :(
     /*   Point BoxMovement = MyPictureBox.Location; //create a point called BoxMovement 
        BoxMovement.X += distance; // Adjust the X of that by distance. 
        MyPictureBox.Location = BoxMovement; // now adjust the Box by the Point's location. 
     */ 


    } 
} 

}

답변

1

것은, 왜 그냥에게 액세스 권한을 부여하지 않습니다 ? 메서드에 인수로 전달하는 것. 단추 2의 클릭 이벤트 처리기에서 지금

public void MoveThatPic(PictureBox picBox, int distance) // New method, 
             // takes a variable called Distance. 

{ 
    MessageBox.Show(distance.ToString()); // Just show us that Variable. 


    // I need to be able to access Form1's picture box before I can use this. :(
    Point BoxMovement = picBox.Location; //create a point called BoxMovement 
    BoxMovement.X += distance; // Adjust the X of that by distance. 
    picBox.Location = BoxMovement; // now adjust the Box by the Point's location. 
} 

:

당신이 그에게 개체를 이동 한 후 위치를 변경 클래스 (MyPictureBox.Location)에서 위치를 잡는 것 같은 튜토리얼 코드가 보이는
private void button2_Click(object sender, EventArgs e) 
{ 
    PicMover PicMoverObject1 = new PicMover(); // Reserve Space for&Create object 
    PicMoverObject1.MoveThatPic(MyPictureBox, 5); // Execute Object Method with a value of 5 
} 
+0

그랬어! 나는 INT 변수처럼 PictureBox 객체를 전달할 수 있다는 것을 깨닫지 못했지만 두 객체 모두라는 것을 깨달았어야합니다. 감사합니다. :) – user236494

0

새로운 위치.

Point p = MyPictureBox.Location // Save the location of your object 
p.x += distance; // Increase the distance 
MyPictureBox.Location = p // Set your object to the new location 

두 번째 버튼 누름 이벤트가 다릅니다. 아마도 함수에서 위치를 반환해야합니까? 따라서 함수를 호출 할 때 기본 폼의 PictureBox를 반환 된 값으로 설정합니다.

+0

나는 그런 것을 고려하고 있었지만, 그것은 메인 폼에 PictureBox 컨트롤을 남겨 둘 필요가 있었고, 튜토리얼의 기준에 맞추기 위해 클래스 내에서 그것들을 사용해야했습니다. 디어차오 (Deerchao)는 그 일을하는 방법에 대해 알려 주셨지만 그 대답에 감사드립니다! – user236494

0

어떤 폼에서든지 액세스 할 수있는 범용 클래스를 만들고 싶다면 그 인스턴스를 만듭니다 ... F orm에있는 PictureBox를 이동하려면 'Deerchao의 대답을 통해 그것을하기 위해.

비록 ... 고려하십시오 ... 모든 양식은 PicMover 자신의 인스턴스를 선언 할 예정입니다; PicMover의 Form1 인스턴스는 사용자가 어떻게 든 게시하지 않는 한 다른 양식에 "표시"되지 않습니다.

기술적으로 더 자세히 설명하면, 여기에 정의 된대로 PicMover 클래스는 응용 프로그램 이름 공간의 범위에 있습니다. 응용 프로그램의 모든 클래스가 인스턴스를 만들기 위해 사용할 수있는 객체 유형을 만들기위한 템플릿이지만 응용 프로그램의 클래스는 기본값으로 인 의 인스턴스를 "갖습니다".

다음은 "주입"을 보여주는 훌륭한 답변에 대한 대안입니다. 주입은 클래스의 인스턴스가 참조를 "유지"하기를 원할 때 적절합니다.이 예에서는 Form의 PictureBox 인스턴스가 " 를 Form1의 PictureBox를 참조 개최 PicMover 다음 '

우리는 클래스 내에서 공용 속성을 선언 PicMover 클래스'의 인스턴스에 "바인딩을 Form1에 따라서

public class picMover 
{ 
    // note use of C# 3.0 automatic property feature here 
    public PictureBox myPictureBox { get; set; } 

    public void movePic(int distance) 
    { 
     // note test for null here 
     if (myPictureBox != null) 
     { 
      myPictureBox.Left += distance; 
     } 
    } 
} 

을 당신의 인스턴스를 만든 후 'PicMover, 내부 PictureBox 속성을 설정 한 다음 내부'movePic m ethod : IMHO, 그것을 사용하기 전에 널 (null)을 테스트하여 확인 대상에 "주입"참조가 존재하는지 확인하기 위해 테스트하는 것은으로 얻을 수있는 좋은 습관 것을

// instance of PicMover created in the Form's scope 
picMover myPicMover = new picMover(); 

private void Form1_Load(object sender, EventArgs e) 
{ 
    // when the Form loads inject the reference to the PictureBox instance into the instance of 'PicMover 
    myPicMover.myPictureBox = pictureBox1; 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    myPicMover.movePic(23); 
} 

참고 :이있다.

PictureBox 객체의 인스턴스를 'PicMover'의 인스턴스에 "바인딩"할 수있는 또 다른 방법은 PictureBox의 인스턴스를 매개 변수로 클래스 생성자에 전달하는 것입니다. 이것, 누군가는 이미 그 기술을 보여주는 대답을 올릴 것입니다. 내부 참조가 변경 될 것으로 예상 될 때 여기에 표시된 Public 속성을 사용하여 "주입"할 수 있습니다. 변경되지 않을 것으로 예상 할 때 PictureBox를 클래스 생성자에 전달할 수 있습니다.

또 다른 전략은 '정적 인 정적 방법으로'PicMover를 정적 인 정적 클래스로 만드는 것입니다. 그러면 모든 양식에서 '볼 수 있습니다'. 양식을 만들 필요가 없습니다. "instance"는 정적 클래스입니다. 원하는 경우 : 정적 클래스입니다.)