중첩 구조체 사용하기
추천 자료: ASP.NET Core 인증 및 권한 부여
이번에는 중첩 구조체, 즉 구조체 안에 다른 구조체를 사용하는 방법에 대해 알아보고, 이를 활용하는 간단한 예제를 살펴봅니다.
코드: NestedStructures.cs
using System;
namespace NestedStructures
{
// 주소 정보를 나타내는 구조체
struct Address
{
public string Street; // 거리명
public string City; // 도시명
public string ZipCode;// 우편번호
}
// 학생 정보를 나타내는 구조체
struct Student
{
public string Name; // 학생 이름
public Address StudentAddress; // 주소 정보 (Address 구조체를 사용)
}
class Program
{
static void Main()
{
// 학생 구조체 변수를 초기화. 주소 정보도 함께 초기화한다.
Student student1 = new Student();
student1.Name = "철수";
student1.StudentAddress = new Address { Street = "123번길", City = "서울", ZipCode = "12345" };
// 학생 정보를 출력
Console.WriteLine("이름: " + student1.Name);
Console.WriteLine("주소: " + student1.StudentAddress.Street + ", " + student1.StudentAddress.City + ", " + student1.StudentAddress.ZipCode);
}
}
}
이름: 철수
주소: 123번길, 서울, 12345
위 예제에서는 두 개의 구조체를 정의하고 있습니다. 첫 번째 구조체인 Address
는 주소 정보를 표현하는 데 사용되며, Street
, City
, ZipCode
라는 멤버 변수를 가지고 있습니다. 두 번째 구조체인 Student
는 학생의 정보를 표현하는데 사용됩니다. 이 구조체는 Name
이라는 멤버 변수와 Address
타입의 StudentAddress
라는 멤버 변수를 가지고 있습니다.
Main
메서드에서는 Student
타입의 student1
변수를 생성하고 초기화합니다. 중첩 구조체인 StudentAddress
도 초기화하는 과정에서 함께 초기화됩니다.
마지막으로, Console.WriteLine()
메서드를 사용하여 학생의 이름과 주소 정보를 출력합니다.
추천 자료: .NET Blazor에 대해 알아보시겠어요? .NET Blazor 알아보기를 확인해보세요!