구조체 struct

Gogi·2023년 9월 6일

C# 언어 기초 목록

목록 보기
8/29

구조체 Structs (C++의 구조체와 다름)

  • 클래스와 차이점

    • 값 타입
    • 상속 안 됨 (System.Object → System.ValueType 을 상속 받았음)
    • 기본 생성자 선언 X / 필드 이니셜나이저 X / 종료자 X / 가상 또는 protected 멤버 X / null X
  • 기본 생성자 재정의 못함

  • 생성자에서 모든 멤버를 명시적으로 초기화 해야 함

public struct Point
{
int x = 1; // Illegal: 필드 이니셜라이저
int y;
public Point() {} // Illegal: 매개변수가 없는 생성자
public Point (int x) {this.x = x;} // Illegal: 필드를 할당해야함
}

  • Point() 생성자는 암시적으로 추가됨 (멤버들을 디폴트 값으로 할당함)

public struct Point
{
int x, y;
public Point (int x, int y) { this.x = x; this.y = y; }
}
...
Point p1 = new Point (); // p1.x and p1.y will be 0 암것도 안 쓰면 걍 0(디폴트 값)임 (Point p1 = default;)
Point p2 = new Point (1, 1); // p2.x and p2.y will

Point p1 = default;
default 키워드는 기본 생성자와 같은 일을 함

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

읽기전용 구조체/함수 Read-Only Structs and Functions

  • readonly 메소드에서 필드를 수정하려 하면 에러 / 일반 메소드를 호출하면 경고
    readonly struct Point
    {
    public readonly int X, Y; // X and Y must be readonly 컴파일러 최적화 여지
    }

이 키워드가 붙으면 readonly 만 불러올 수 있다

Ref Structs

  • 값 형식임에도 스택 영역에 올라갈 수 있다

  • 구조체의 인스턴스는 변수가 어디 선언 됐는지에 따라 힙 영역인지 스택영역인지 결정된다.

  • 지역 변수나 파라미터인 경우 스택영역

  • 클래스의 멤버일 경우 힙영역

'Stack 영역'
void SomeMethod()
{
Point p; // p will reside on the stack
}
struct Point { public int X, Y; }

'구조체의 배열 또한 힙 영역'
class MyClass
{
Point p; // Lives on heap, because MyClass instances live on the heap
}

'ref struct 는 인스턴스가 스택 영역에만 존재하도록 제한한다.'

var points = new Point [100]; // Error: will not compile!

ref struct Point { public int X, Y; }
class MyClass { Point P; } // Error: will not compile!

profile
C, C++, C#, Unity

0개의 댓글