[C#] 구조체(Struct)와 생성자, this 키워드

2023. 8. 8. 15:58C#

728x90
반응형

구조체는 클래스와 마찬가지로 변수와 함수로 이루어져 있다. 

 

 

  • 데이터 중심 기반 구조체 (C 언어)
public class TestScript : MonoBehaviour
{
    public struct StructPos
    {
        public int x;
        public int y;
        public int z;
    }
    // Start is called before the first frame update
    void Start()
    {
        StructPos pos;
        pos.x = 10;
        pos.y = 20;
        pos.z = 30;
        print("x : " + pos.x + " y : " + pos.y + " z : " + pos.z);
    }
}

 

 

  • 객체 기반 구조체 (C# 언어)

-내용은 모르는 채로 함수만 쓸 수 있는 경우

public class TestScript : MonoBehaviour
{
    public struct StructPos
    {
        public int x;
        public int y;
        public int z;
        public void Show()
        {
            print("x : " + x + " y : " + y + " z : " + z);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        StructPos pos;
        pos.x = 10;
        pos.y = 20;
        pos.z = 30;
        pos.Show();
    }
}

변수 pos를 선언하여 사용한 것을 볼 수 있다.

 

 


 

 

구조체와 생성자

public class TestScript : MonoBehaviour
{
    public struct StructPos
    {
        public int x;
        public int y;
        public int z;
        public void Show()
        {
            print(x + " " + y + " " + z + " ");
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        StructPos pos = new StructPos();
        pos.Show();
    }
}

생성자를 사용한 모습이다. 생성자는 구조체나 클래스의 초기화 담당 함수인데, 위에서는 StructPos(); 라는 기본 생성자를 만들어 주었다. x, y, z 모두 0으로 초기화 된다.

 

 

public class TestScript : MonoBehaviour
{
    public struct StructPos
    {
        public int x;
        public int y;
        public int z;
        public StructPos(int xIn, int yIn, int zIn)
        {
            x = xIn;
            y = yIn;
            z = zIn;
        }
        public void Show()
        {
            print(x + " " + y + " " + z + " ");
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        StructPos pos = new StructPos(10, 20, 30);
        pos.Show();
    }
}

생성자에서 값을 입력받고 싶을 때는 위와 같이 표현하면 된다.

 

 


 

 

this 키워드

구조체나 클래스 자기 자신이 가지고 있는 변수에 사용 가능하다.

public class TestScript : MonoBehaviour
{
    public struct StructPos
    {
        public int x;
        public int y;
        public int z;
        public StructPos(int x, int y, int z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }
        public void Show()
        {
            print(x + " " + y + " " + z + " ");
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        StructPos pos = new StructPos(10, 20, 30);
        pos.Show();
    }
}

this.x; 는 public int x;와 같다.

728x90
반응형