C#에서 구조체는 값 형식 데이터 형식입니다. 하나의 변수에 다양한 데이터 유형의 관련 데이터를 담을 수 있도록 도와줍니다. struct 키워드는 구조를 만드는 데 사용됩니다.
구조를 정의하려면 struct 문을 사용해야 합니다. struct 문은 프로그램에 대해 둘 이상의 멤버가 있는 새 데이터 유형을 정의합니다.
예를 들어 Book 구조를 선언하는 방법은 다음과 같습니다.
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
}; 다음은 C#에서 구조체를 생성하는 방법을 보여주는 예시입니다.
예시
using System;
struct Books {
public string title;
public string author;
public string subject;
public int book_id;
};
public class testStructure {
public static void Main(string[] args) {
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
} 출력
Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id :6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700