본문 바로가기
언어 정리/C# 개념 및 lib

구조체, 인터페이스, 열거형(enum), 튜플, 네임드튜플, 딕셔너리, Nullable

by 알 수 없는 사용자 2024. 1. 9.

 

자료형 종류 및 예시

  1. 값 형식 (Value Types)
    • 기본 자료형 (Primitive Types): int, float, double, bool, char 등
    • 구조체 (Structs): DateTime, TimeSpan 등
    • 열거형 (Enums): 사용자 정의 열거형
  2. 참조 형식 (Reference Types)
    • 클래스 (Classes): object, string 등
    • 인터페이스 (Interfaces)
    • 배열 (Arrays)
    • 대리자 (Delegates)
  3. 컬렉션 (Collections)
    • List<T>: 가변 크기의 순차적 목록
    • LinkedList<T>: 양방향 연결 목록
    • Queue<T>: FIFO (선입선출) 구조
    • Stack<T>: LIFO (후입선출) 구조
    • HashSet<T>: 유일한 요소를 저장하는 집합
    • Dictionary<TKey, TValue>: 키-값 쌍을 저장하는 컬렉션
    • SortedDictionary<TKey, TValue>: 키에 따라 정렬된 키-값 쌍을 저장하는 컬렉션
    • SortedList<TKey, TValue>: 배열 기반의 정렬된 키-값 쌍 컬렉션
  •  

 

 


구조체, 인터페이스, 열거형(enum), 튜플, 네임드튜플, 딕셔너리, Nullable

ex) 코드 : 

using System;
using System.Collections.Generic;

// ==================================== struct ====================================
public struct Point  // struct 형식에서 다른 struct 형식을 파생할 수 없으며 암시적으로 봉인됩니다.
{
    public double X { get; }
    public double Y { get; }
    
    public Point(double x, double y) => (X, Y) = (x, y);
}

// ==================================== interface ====================================
// 1
interface IControl
{
    void Paint();
}

interface ITextBox : IControl
{
    void SetText(string text);
}

interface IListBox : IControl
{
    void SetItems(string[] items);
}

interface IComboBox : ITextBox, IListBox { }

// 2
interface IDataBound
{
    void Bind(int b);
}

public class EditBox : IControl, IDataBound
{
    public void Paint() { }
    public void Bind(int b) { }
}

// ==================================== enum ====================================
public enum SomeRootVegetable
{
    HorseRadish,
    Radish,
    Turnip
}

[Flags]
public enum Seasons
{
    None = 0,
    Summer = 1,
    Autumn = 2,
    Winter = 4,
    Spring = 8,
    All = Summer | Autumn | Winter | Spring
}


// ==================================== main ====================================
class Program
{
    static void Main()
    {
        // ==================================== interface ====================================
        EditBox editBox = new EditBox();
        editBox.Paint();
        int i_number = 2;
        editBox.Bind(i_number);
        IControl control = editBox;
        IDataBound dataBound = editBox;
        
        // ==================================== enum ====================================
        var turnip = SomeRootVegetable.Turnip;
        var spring = Seasons.Spring;
        var startingOnEquinox = Seasons.Spring | Seasons.Autumn;
        var theYear = Seasons.All;
        // 결과 출력
        Console.WriteLine($"A: {turnip},\t\t B: {SomeRootVegetable.Radish}");
        Console.WriteLine($"A: {spring},\t\t B: {(int)spring}");
        Console.WriteLine($"A: {startingOnEquinox},\t B: {startingOnEquinox & Seasons.Autumn}");
        Console.WriteLine($"A: {theYear & Seasons.Winter},\t\t B: {(int)(theYear & Seasons.Winter)}");
        
        // ==================================== Nullable ====================================
        int? optionalInt = default; 
        Console.WriteLine($"C: { (optionalInt is null) }");  // True
        optionalInt = 5;
        string? optionalText = default;
        Console.WriteLine($"C: { (optionalText == null) }");  // True
        optionalText = "Hello World.";
        
        // ==================================== Tuple ====================================
        (double index_1, int index_2) t2 = (9.99, 9);
        ValueTuple<int, int, int, int> t3 = (1, 2, 3, 4);
        var t4 = (5, 6);
        var t5 = (7, 8, 9, 10, "11", "12");
        
        Console.WriteLine($" t2 : {t2} , t3 : {t3} , t4 : {t4} , t5 : {t5}");
        Console.WriteLine($" >> : {t2.index_2} , >> : {t2.Item2}");
        
        // ==================================== Named Tuple ====================================
        var namedTuple = (First: 1, Second: 2, Third: 3, Fourth: 4);
        
        Console.WriteLine(namedTuple.First); // 출력: 1
        Console.WriteLine(namedTuple.Second); // 출력: 2
        
        // ==================================== dictionary ====================================
    /* Dictionary 선언방법 1*/
    Dictionary<string, int> ex_1 = new Dictionary<string, int>();
    /* Dictionary 선언방법 2*/
    Dictionary<string, int> ex_2 = new Dictionary<string, int>()
    {
        ["t1"] = 1,
        ["t2"] = 2,
    };
    /* Dictionary 선언방법 3*/
    Dictionary<string, int> ex_3 = new Dictionary<string, int>()
    {
        { "liam", 31 },
        { "gen", 20 },
    };

    // 값 추가 1
    ex_3.Add("Alice", 30);
    // 값 추가 2
    ex_3["Bob"] = 25; 

    // 값 꺼내오기
    Console.WriteLine(ex_3["Alice"]); // 출력: 30

    // Key 검사 1
    if (ex_3.ContainsKey("Bob"))
    {
        Console.WriteLine($"Bob is exist : {ex_3["Bob"]}");  // 출력: Bob is exist : 25
    }
    // Key 검사 2
    if (ex_3.TryGetValue("Bob", out var bobAge))
    {  // ex_3 딕셔너리에 Bob 라는 key가 있으면 bobAge 변수에 대입한다.
        Console.WriteLine($"Bob is exist : {bobAge}");  // 출력: Bob is exist : 25
    }

    // 값 업데이트
    ex_3["Alice"] = 31; // Alice의 나이를 31로 업데이트

    // 값 삭제
    ex_3.Remove("Bob"); // Bob의 키와 값을 삭제

    // Dictionary 내용 출력
    foreach (KeyValuePair<string, int> pair in ex_3)
    {
        Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
        /*  Name: liam, Age: 31
            Name: gen, Age: 20
            Name: Alice, Age: 31    */
    }
    }
}

 

 

 

 

'언어 정리 > C# 개념 및 lib' 카테고리의 다른 글

vscode with c# in wsl  (1) 2024.01.23
참조자, static method, 오버라이딩, 오버로드  (1) 2024.01.09
상속과 다형성  (1) 2024.01.09
생성자  (0) 2024.01.09
var, foreach, List 자료형  (0) 2024.01.08

댓글