2012-09-11 4 views
1

나는 책을 따라 가면서 시작하기가 다소 어려운 초보자입니다. 나는 책을 읽고 코드가 무엇을하는지보기 위해 코드를 컴파일 할 것이다. 저는 구조체의 섹션, 특히 구조체 변수에 있습니다. 다음 코드는 point does not take two arguments입니다. 누군가 나를 놓치거나 부정확 한 점을 발견하도록 도울 수 있습니까? 감사. 당신이 인수를 호출하기 때문에구조 변수 만들기 C#

using System; 

    class Program 
    { 
     static void Main(string[] args) 
     { 

      // Create an initial Point. 
      Point myPoint; 
Point p1 = new Point(10, 10); 
      myPoint.X = 349; 
      myPoint.Y = 76; 
      myPoint.Display(); 
      // Adjust the X and Y values. 
      myPoint.Increment(); 
      myPoint.Display(); 
      Console.ReadLine(); 
     } 
     // Assigning two intrinsic value types results in 
     // two independent variables on the stack. 
     static void ValueTypeAssignment() 
     { 
      Console.WriteLine("Assigning value types\n"); 
      Point p1 = new Point(10, 10); 
      Point p2 = p1; 
      // Print both points. 
      p1.Display(); 
      p2.Display(); 
      // Change p1.X and print again. p2.X is not changed. 
      p1.X = 100; 
      Console.WriteLine("\n=> Changed p1.X\n"); 
      p1.Display(); 
      p2.Display(); 
     } 
    } 


    struct Point 
    { 
     // Fields of the structure. 
     public int X; 
     public int Y; 
     // Add 1 to the (X, Y) position. 
     public void Increment() 
     { 
      X++; Y++; 
     } 
     // Subtract 1 from the (X, Y) position. 
     public void Decrement() 
     { 
      X--; Y--; 
     } 
     // Display the current position. 
     public void Display() 
     { 
      Console.WriteLine("X = {0}, Y = {1}", X, Y); 
     } 

    } 
+3

인수를 취하는 Point의 생성자가 없습니다. – Joe

답변

7

당신은) (10, 10, Point에 두 개의 매개 변수를 생성자를 추가해야합니다.

Point myPoint = new Point(); 
myPoint.X = 349; 
myPoint.Y = 76; 

그위한 속기는 다음과 같습니다 :

Point myPoint = new Point { X = 349, Y = 76 }; 

그런 다음 내장 인수 없음 (무 매개 변수)와 생성자를 구성 할 수 있습니다 또는

struct Point 
{ 
    // Fields of the structure. 
    public int X; 
    public int Y; 

    public Point(int x, int y) 
    { 
     X = x; 
     Y = y; 
    } 

는 속성을 설정 또는 심지어 더 짧다 :

var myPoint = new Point { X = 349, Y = 76 }; 

마지막으로 구조체를 변경할 수 없도록 만드는 것이 일반적으로 좋은 습관입니다. 일단 구성되면 내용을 수정할 수 없어야합니다. 이렇게하면 언어에서 많은 함정을 피할 수 있습니다.

+0

자리에 있습니다. 감사합니다 :) +1 여분의 마일 가고 다른 선언의 동등한를 보여주는 +1. – wootscootinboogie

+3

불변성에 대한 좋은 지적. –

0

두 개의 매개 변수를 사용하는 Point에는 생성자가 없습니다.

당신이 필요합니다

public Point(int x, int y){ // assign these to your properties. } 
4

대신 두 개의 인수 생성자를 사용하여 포인트를 구성, 같은 호출의 일부로서 속성을 인스턴스화합니다. 예를 들면 다음과 같습니다.

Point p = new Point { X = 1, Y = 2 }; 

추가 코드를 작성하지 않고도 단일 회선 구성을 이용할 수 있습니다. 메인에 포인트를 초기화해야

public Point(int x, int y) 
{ 
    X = x; 
    Y = y; 
} 
+0

@ DanielEarwicker 감사합니다. 확인하지 않고 코드를 너무 빨리 입력했습니다. 코드가 수정되었습니다. – akton

0

당신은 포인트 구조체에 대한 생성자를 누락?

Point myPoint = new Point(); 
0

망가 :

0

두 개의 매개 변수가 정의 된 생성자가 없습니다. 포인트 구조체가 유효해야합니다.

public Point(int x, int y) 
{ 
    X = x; 
    Y = y; 
}