반도체, 임베디드 Study/C#

C# - 구조체 / 열거형

잇(IT) 2024. 4. 15. 10:42
728x90

구조체란?

 

기존의 변수와 배열은 하나의 이름으로 하나의 데이터 형식을 가지고 공간을 차지했다.

 

구조체란 변수와 배열을 확장하여 하나의 이름으로 여러 개의 데이터 형식을 한 개 또는 여러 개 보관하는 그릇 역할을 하는 것이 바로 구조체(struct)이다.

구조체 변수란 하나의 이름으로 하나 이상의 데이터 형식을 하나 보관해 놓는 그릇 역할이고, 구조체 배열은 하나의 이름으로 하나 이상의 데이터 형식을 여러 개 보관해 놓는 그릇 역할을 하는 것으로 볼 수 있다.

 

 

1. Data Type 정의

2. 해당 Type의 변수 선언

3. 해당 구조체 사용

 

구조체 선언 모양

struct 구조체명
{
    데이터형식 변수1;
    데이터형식 변수2;
    데이터형식 변수3; 
}

구조체를 의미하는 struct 키워드를 사용하여 구조체를 만들고, 중관호 안에 구조체 멤버들을 생성한다.

   여기에서 구조체 이름은 새로운 데이터 형식이 되며, 변수를 선언할 때 구조체 이름을 사용할 수 있다.

   구조체를 가리켜 사용자 정의 데이터 형식이라고도 한다.

 

ex)

namespace structEx
{
    class Program
    {

        struct Point
        {
            public int x;
            public int y;
        }
        static void Main(string[] args)
        {
            Point p;
            p.x = 100;
            p.y = 200;

            Console.WriteLine($"{p.x}, {p.y}");
        }
    }
}

 

 

구조체 배열

명함구조체[] 명함배열 = new 명함구조체[1000];

 

 

ex)

namespace structEx
{
    class Program
    {

        struct Student
        {
            public int A;
            public int B;
            public int C;
            public int sum;
            public double avg;
        }
        static void Main(string[] args)
        {
            Student s; //s라는 변수 안에 A, B, C, sum, avg가 포함된다.
            s.A = 100;
            s.B = 200;
            s.C = 300;

            Student[] students = new Student[5];

            students[0].A = 500;
            students[0].B = 600;

            students[1].A = 5000;

            students[4].A = 50000000;

            for (int i = 0; i<5; i++)
            {
                Console.WriteLine($"{students[i].A}, {students[i].B}");
            }
        }
    }
}

구조체 배열을 통해 변수를 입력하고, for문을 통해 구조체 배열에 입력된 값들을 확인할 수 있다.

 

구조체 매개 변수 

using System;

// Member 구조체 선언
struct Member
{
    public string Name;
    public int Age;
}

class StructParameter
{
    static void Main()
    {
        //[1] 변수 사용
        string name = "홍길동";
        int age = 21;
        Print(name, age); // 매개 변수를 따로 선언

        //[2] 구조체 사용 
        Member m;
        m.Name = "백두산";
        m.Age = 100;
        Print(m); // 구조체 매개 변수를 사용하여 전달
    }

    static void Print(string name, int age) =>
        Console.WriteLine($"이름: {name}, 나이: {age}");

    static void Print(Member member) =>
        Console.WriteLine($"이름: {member.Name}, 나이: {member.Age}");
}

위와 같이 구조체 Member를 생성한 뒤 Print 함수의 매개변수로 구조체를 입력할 수 있다.


 

내장형 구조체

DateTime 구조체: 시간/날짜 관련된 모든 정보를 제공합니다.
TimeSpan 구조체: 시간/날짜 간격에 대한 모든 정보를 제공합니다.
Char 구조체: 문자 관련 모든 정보를 제공합니다. 예를 들어, 특정 문자가 숫자 형식인지 기호 문자인지 공백 문자인지 등을 판단하는 기능을 제공합니다.
Guid 구조체: 절대로 중복되지 않는 유일한 문자열을 생성해줍니다.

 

TimeSpan 구조체 ex)

namespace netStruct
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeSpan dDay = Convert.ToDateTime("2024-12-25") - DateTime.Now;
            Console.WriteLine($"{DateTime.Now.Year}년도 크리스마스는 {(int)dDay.TotalDays}일 남음");

            TimeSpan times = DateTime.Now - Convert.ToDateTime("1995-04-17");
            Console.WriteLine($"내가 지금까지 살아온 년도와 날짜는 {(int)times.TotalDays}일 살아왔고, {((int)times.TotalDays / 365)}년 살아왔습니다.");
        }
    }
}


구조체 배열을 이용한 학생 점수 합, 평균 구하기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 5명, 이름 - string, 과목 - int, 합 - int, 평균 - double
// 5명 정보 입력
// 출력 A, B, sum, avg 계산을 해서 출력
namespace structStudent
{
    class Program
    {
        struct Student
        {
            public string name;
            public int A, B;
            public int sum;
            public double avg;
        }
        static void Main(string[] args)
        {
            Student[] s = new Student[5];

            // 이름 및 A, B 과목
            for(int i = 0; i < 5; i++)
            {
                Console.WriteLine($"{i+1}번째 이름을 입력하세요 : ");
                s[i].name = Console.ReadLine();
                Console.WriteLine($"{i+1}번째 A과목 점수를 입력하세요 : ");
                s[i].A = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine($"{i+1}번째 B과목 점수를 입력하세요 : ");
                s[i].B = Convert.ToInt32(Console.ReadLine());
                s[i].sum = s[i].A + s[i].B;
                s[i].avg = s[i].sum / 2;
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine("*******입력한 학생 정보입니다.*******");

            for(int i = 0; i < 5; i++)
            {
                Console.WriteLine($"{i}번째 학생 이름은 : {s[i].name}");
                Console.WriteLine($"{i}번째 학생의 A과목 점수는 : {s[i].A}");
                Console.WriteLine($"{i}번째 학생의 B과목 점수는 : {s[i].B}");
                Console.WriteLine($"{i}번째 학생 A, B 과목 점수 합은 : {s[i].sum}");
                Console.WriteLine($"{i}번째 학생 A, B 과목 점수의 평균은 : {s[i].avg}");
                Console.WriteLine();
            }

        }
    }
}

 


열거형

 

열거형(Enumeration) 형식은 기억하기 어려운 상수들을 기억하기 쉬운 하나의 이름으로 묶어 관리하는 표현 방식이다.

열거형을 사용하면 여러 개의 값 리스트를 하나의 이름으로 관리할 수 있다. 열거형은 enum 키워드를 사용한다.

 

열거형 배경색 바꾸기 ex)

namespace netStruct
{
    class Program
    {
        static void Main(string[] args)
        {
            // 열거형 예제
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("Blue");
            Console.ResetColor();

            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Red");
            Console.ResetColor();
        }
    }
}

 

 

열거형 만들기

enum 열거형명
{
    열거형상수1,
    열거형상수2,
    열거형상수3
}

enum 열거형명
{
    열거형상수1 = 기본값1,
    열거형상수2 = 기본값2,
    열거형상수3 = 기본값3
}

 

 

지정된 열거형의 상수 리스트를 배열로 가져오기

using System;

class EnumGetNames
{
    static void Main()
    {
        // ConsoleColor 열거형의 Type을 cc 변수에 저장
        Type cc = typeof(ConsoleColor);
        
        // 모든 색상 이름을 반환
        string[] colors = Enum.GetNames(cc);

        // 출력
        foreach (var color in colors)
        {
            Console.WriteLine(color);
        }
    }
}

 

 

열거형 상수, 지정된 값 가져오기

namespace netStruct
{
    class Program
    {
        enum size
        {   
            Short,
            Tall,
            Grande,
            Vent
        }

        enum price
        {
            Short = 3000,
            Tall = 4000,
            Grande = 5000,
            Vent = 6000
        }
        static void Main(string[] args)
        {
            Type price_cc = typeof(price);
            Type size_cc = typeof(size);

            int[] prices = Enum.GetValues(price_cc) as int[];
            string[] sizes = Enum.GetNames(size_cc);

            foreach(int p in prices)
            {
                Console.WriteLine($"{p}");
            }

            Console.WriteLine();

            foreach(string s in sizes)
            {
                Console.WriteLine($"{s}");
            }
        }
    }
}

 

 

 


Public이 붙어있으면 다른 클래스에 있는 변수도 가져다가 쓸 수 있는 것이다.

728x90