[C#] 구조체 Struct

c# 2023. 1. 9. 10:58
728x90

단순하지만 데이터 타입이라는 집합들을 관리하고 정의할때 사용

 

struct person
{
	public string name;
    public int age;
    public int empid;
    
    public person(string name, int age, int empid)
    {
    	this.name = name;
        this.age = age;
        this.empid = empid;
    }
}

static void main(string[] args)
{
	person _person = new person("철수", 25.20210401);
    Console.WriteLine("이름:{0} 나이:{1} 사번:{2}", _person.name, _person.age, _person.empid);
}

 

readonly 구조체

readonly를 사용하면 구조체 형식을 변경할 수 없음 (읽기 전용)

readonly 구조체는 모든 필드 선언에 readonly 한정자가 있어야한다

생성자를 제외한 다른 인스턴스 멤버는 암시적으로 readonly 이다

readonly 구조체에서 변경 가능한 참조 형식의 데이터 멤버는 여전히 자체 상태를 변경할 수 있다

예를 들어 List<T> 인스턴스를 바꿀 수는 없지만 새 요소를 추가할 수는 있다

 

public readonly struct Coords
{
	public Coords(double x, double y)
    {
    	X = x;
        Y = y;
    }
    
    public double X {get; init;}
    public double Y {get; init;}
    
    public readonly double Sum()
    {
        return X + Y;
    }

    public override string ToString() => $"({x}, {y})";
}

 

구조체 초기화 및 기본값

struct 형식의 변수는 struct에 대한 데이터를 직접 포함한다

그러면 기본값 있는 초기화 되지 않은 struct과 생성된 값을 저장하여 초기화 하는 struct 이 구분된다

 

public readonly struct Measurement
{
    public Measurement()
    {
        Value = double.NaN;
        Description = "Undefined";
    }

    public Measurement(double value, string description)
    {
        Value = value;
        Description = description;
    }

    public double Value { get; init; }
    public string Description { get; init; }

    public override string ToString() => $"{Value} ({Description})";
}

public static void Main()
{
    var m1 = new Measurement();
    Console.WriteLine(m1);  // output: NaN (Undefined)

    var m2 = default(Measurement);
    Console.WriteLine(m2);  // output: 0 ()

    var ms = new Measurement[2];
    Console.WriteLine(string.Join(", ", ms));  // output: 0 (), 0 ()
}

 

 

728x90
Posted by 바르마스
,