C# - 클래스 Static 실습 문제 풀이

2025. 9. 19. 00:08·C#

과제1 ) static 직접 만들어 보기

일반 클래스를 하나 만든 후, 맴버 변수로 private static 정수를 하나 가지게 하자. 일반 클래스 public 메서드로 해당 static 정수를 하나 1 올리는 메서드와, 해당 static변수를 출력시키는 메서드를 하나 만들어보자. 전부 제작 후, 메인에서 방금 만들어진 클래스로 객체를 3개 만든 후, 방금 만들어진 두 함수를 다양하게 실행해보자

※ 클래스명, 필드, 메서드명 본인이 자유롭게

 

using System;

namespace StaticTask
{
    class Normal
    {
        private static int num;

        public void IncreaseNum()
        {
            num++;
        }
        public void PrintNum()
        {
            Console.WriteLine(num);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Normal normal1 = new Normal();
            Normal normal2 = new Normal();
            Normal normal3 = new Normal();

            normal1.IncreaseNum();
            normal2.IncreaseNum();
            normal3.IncreaseNum();

            normal1.PrintNum();
            normal2.PrintNum();
            normal3.PrintNum();
        }
    }
}

// 3 3 3 출력

 

 

 

과제 2 ) satic 접근법 체험하기

아까 만든 클래스에서 static 변수를 public 으로 바꾸어 보자. 그 후, 메인에서 [클래스명.스태틱변수] int형에 담거나 출력해보는 코드를 작성하여 에러가 나는지 안나는지 확인하여보자.

 

using System;

namespace StaticTask
{
    class Normal
    {
        //private static int num;
        public static int num;

        public void IncreaseNum()
        {
            num++;
        }
        public void PrintNum()
        {
            Console.WriteLine(num);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Normal normal1 = new Normal();
            Normal normal2 = new Normal();
            Normal normal3 = new Normal();

            normal1.IncreaseNum();
            normal2.IncreaseNum();
            normal3.IncreaseNum();

            normal1.PrintNum();
            normal2.PrintNum();
            normal3.PrintNum();

            Console.WriteLine(Normal.num);
        }
    }
}
// 3 3 3 3

 

 

 

과제 3 ) static 프로퍼티 체험하기

위 클래스에서 static 변수를 다시 private으로 바꾸고, 프로퍼티를 활용하여, 접근이 가능한지 알아보자. 방금 만든 public 프로퍼티에도 static을 붙여서 위 변수 접근처럼 [클래스명.프로퍼티]로 접근이 가능한지 알아보고, static이 아닌 일반 정수형을 하나 만든 후, public static 프로터피로 일반 정수형을 다룰 수 있는지 알아보자.

 

using System;

namespace StaticTask
{
    class Normal
    {
        private static int num;
        int normalNum;

        static public int StaticNum
        {
            get { return num; }
            set { num = value; }
        }

        public int NormalNum
        {
            get { return normalNum; }
            set { num = value; }
        }

        public void IncreaseNum()
        {
            num++;
        }
        public void PrintNum()
        {
            Console.WriteLine(num);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Normal normal1 = new Normal();
            Normal normal2 = new Normal();
            Normal normal3 = new Normal();

            normal1.IncreaseNum();
            normal2.IncreaseNum();
            normal3.IncreaseNum();

            normal1.PrintNum();
            normal2.PrintNum();
            normal3.PrintNum();

            //Console.WriteLine(Normal.NormalNum); // 안됨
            Console.WriteLine(normal1.NormalNum); // 0
            //Console.WriteLine(normal1.StaticNum); // 안됨
            Console.WriteLine(Normal.StaticNum); // 3
        }
    }
}

 

 

과제 4 ) static 메서드 체험하기

새로운 일반 클래스를 하나 만들고, 맴버 변수로 private static 정수형 하나, 일반 private 정수형 하나를 가지고 있게 하자. 맴버 함수(메소드) public void 형태의 메서드를 만들되, 맴버 변수로 보유중인 스태틱 변수를 +1이 되는 기능을 작성하자. 방금 만든 함수의 void 앞에 static을 붙인 후, 메인에서 [클래스명.함수이름] 이 작동하는지 확인하여보자. 두번째로, 똑같이 public static void 로 일반 맴버변수를 증가시키는 기능을 하나 만든 후, 문제가 생기는지 확인하여보자.

 

using System;

namespace StaticTask
{
    class Normal
    {
        private static int num;
        int normalNum;

        static public int StaticNum
        {
            get { return num; }
            set { num = value; }
        }

        public int NormalNum
        {
            get { return normalNum; }
            set { num = value; }
        }

        public void IncreaseNum()
        {
            num++;
        }
        public void PrintNum()
        {
            Console.WriteLine(num);
        }

    }

    class Another
    {
        private static int num;
        private int normalNum;

        static public void IncreaseStaticNum()
        {
            num++;
        }

        //static public void IncreaseNormalNum() 에러남
        //{
        //    normalNum++;
        //}

        static public void PrintStaticNum()
        {
            Console.WriteLine(num);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Normal normal1 = new Normal();
            Normal normal2 = new Normal();
            Normal normal3 = new Normal();

            normal1.IncreaseNum();
            normal2.IncreaseNum();
            normal3.IncreaseNum();

            normal1.PrintNum();
            normal2.PrintNum();
            normal3.PrintNum();

            //Console.WriteLine(Normal.NormalNum); // 안됨
            Console.WriteLine(normal1.NormalNum); // 0
            //Console.WriteLine(normal1.StaticNum); // 안됨
            Console.WriteLine(Normal.StaticNum); // 3

            Console.WriteLine();
            Console.WriteLine("------------------------------------");
            Console.WriteLine();

            Another.IncreaseStaticNum();
            Another.PrintStaticNum(); // 1

        }
    }
}

 

 

 

과제 5 ) static 메서드에서 static 호출 체험하기

메인으로 가서 방금 만든 클래스를 활용해 객체를 하나 만들어보자. 객체를 통하여 static함수가 호출되는지 확인하여보자. 에러 메세지를 확인한 후, 주석 처리. 일반 맴버 함수로, 맴버 static변수를 출력하는 기능을 하나 작성하고, 맴버 static변수를 두배시키는 static 메소드도 하나 더 만든 후, 함수 내에서 아까 만들어 둔 static변수+1 하는 메소드와, 일반 맴버함수를 호출하여 보자. 어느 부분서 에러가 뜨는지 확인하여보자

 

using System;

namespace StaticTask
{
    class Normal
    {
        private static int num;
        int normalNum;

        static public int StaticNum
        {
            get { return num; }
            set { num = value; }
        }

        public int NormalNum
        {
            get { return normalNum; }
            set { num = value; }
        }

        public void IncreaseNum()
        {
            num++;
        }
        public void PrintNum()
        {
            Console.WriteLine(num);
        }

    }

    class Another
    {
        private static int num;
        private int normalNum;

        static public void IncreaseStaticNum()
        {
            num++;
        }

        static public void DoubleStaticNum()
        {
            num *= 2;
        }

        public void IncreaseNormalNum()
        {
            normalNum++;
        }

        static public void PrintStaticNum()
        {
            Console.WriteLine(num);
        }

        public void PrintNormalNum()
        {
            Console.WriteLine(normalNum);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Normal normal1 = new Normal();
            Normal normal2 = new Normal();
            Normal normal3 = new Normal();

            normal1.IncreaseNum();
            normal2.IncreaseNum();
            normal3.IncreaseNum();

            normal1.PrintNum();
            normal2.PrintNum();
            normal3.PrintNum();

            //Console.WriteLine(Normal.NormalNum); // 안됨
            Console.WriteLine(normal1.NormalNum); // 0
            //Console.WriteLine(normal1.StaticNum); // 안됨
            Console.WriteLine(Normal.StaticNum); // 3

            Console.WriteLine();
            Console.WriteLine("------------------------------------");
            Console.WriteLine();

            Another.IncreaseStaticNum();
            Another.PrintStaticNum(); // 1
            Another.DoubleStaticNum();
            Another.PrintStaticNum(); // 2

            Another another = new Another();
            another.IncreaseNormalNum();
            another.PrintNormalNum(); // 1

        }
    }
}

 

 

 

과제 6 ) static 메서드 내에서 일반 지역변수 활용 체험하기

클래스 내, static메소드에서 static이 아닌 맴버 변수를 활용하는 것은 불가능한것을 확인 하였지만, 이번엔 static 메소드 내에 static을 붙이지 않은 지역변수를 만든 후 문제가 없는지 확인하여보자. 클래스 메소드 속에 static 지역변수는 만들어지는지도 확인하여보자

 

using System;

namespace StaticTask
{
    class Normal
    {
        private static int num;
        int normalNum;

        static public int StaticNum
        {
            get { return num; }
            set { num = value; }
        }

        public int NormalNum
        {
            get { return normalNum; }
            set { num = value; }
        }

        public void IncreaseNum()
        {
            num++;
        }
        public void PrintNum()
        {
            Console.WriteLine(num);
        }

    }

    class Another
    {
        private static int num;
        private int normalNum;

        static public void IncreaseStaticNum()
        {
            num++;
        }

        static public void DoubleStaticNum()
        {
            num *= 2;
        }

        public void IncreaseNormalNum()
        {
            normalNum++;
        }

        static public void PrintStaticNum()
        {
            Console.WriteLine(num);
        }

        public void PrintNormalNum()
        {
            Console.WriteLine(normalNum);
        }

        public static void LocalVariableTest()
        {
            int local = 0; // 일반 지역 변수 -> 문제 없음
            local++;
            Console.WriteLine($"지역 변수 값: {local}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Normal normal1 = new Normal();
            Normal normal2 = new Normal();
            Normal normal3 = new Normal();

            normal1.IncreaseNum();
            normal2.IncreaseNum();
            normal3.IncreaseNum();

            normal1.PrintNum();
            normal2.PrintNum();
            normal3.PrintNum();

            //Console.WriteLine(Normal.NormalNum); // 안됨
            Console.WriteLine(normal1.NormalNum); // 0
            //Console.WriteLine(normal1.StaticNum); // 안됨
            Console.WriteLine(Normal.StaticNum); // 3

            Console.WriteLine();
            Console.WriteLine("------------------------------------");
            Console.WriteLine();

            Another.IncreaseStaticNum();
            Another.PrintStaticNum(); // 1
            Another.DoubleStaticNum();
            Another.PrintStaticNum(); // 2

            Another another = new Another();
            another.IncreaseNormalNum();
            another.PrintNormalNum(); // 1

            Another.LocalVariableTest();
            Another.LocalVariableTest();
        }
    }
}

 

 

 


 

심화 과제 1 )

Math와 같은 클래스는 객체를 만들지 않고도 기능들을 만들어 사용할 수 있음을 배웠습니다. 편리한 사용을 위해 본인만의 myHelper 라는 클래스를 만들었다고 가정하겠습니다. 정수 배열을 입력받아 해당 배열의 요소들 중에서 가장 작은 값을 반환하는 정적 메소드를 하나 작성하세요. 요구 사항은 아래와 같습니다.

  • 입력으로 주어지는 배열은 비어있지 않다고 가정합니다.
  • 정적(static) 메서드를 사용하여 구현하여야 합니다
  • 배열의 모든 요소를 반복하여 가장 작은 값을 찾아 반환하여야 합니다.

 

using System;

namespace StaticTask
{
    class myHelper
    {
        public static void FindMinimum(int[] inputArr)
        {
            int min = inputArr[0];

            foreach (int i in inputArr)
            {
                if (i < min)
                {
                    min = i;
                }
            }

            Console.WriteLine(min);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            int[] ints = new int[10] { 5, 3, 20, 1, 4, 33, -22, 6, 4, 3 };
            myHelper.FindMinimum(ints);
        }
    }
}

 

 

 

심화 과제 2 )

위의 myHelper 클래스에 정적 메소드를 하나 더 만들겠습니다. 주어진 문자열에서 대문자의 개수를 세는 정적 메소드를 구현하세요. 요구 사항은 아래와 같습니다.

  • 입력으로 주어지는 문자열은 비어있지 않다고 가정하겠습니다.
  • 정적 메서드를 사용하여 구현하여야 합니다.
  • 문자열을 반복하여 대문자의 개수를 세고, 그 개수를 반환하여야 합니다.
  • char형의 내장 기능 중, IsUpper를 활용하면 대문자 여부를 확인 가능합니다.

 

using System;

namespace StaticTask
{
    class myHelper
    {
        public static void FindMinimum(int[] inputArr)
        {
            int min = inputArr[0];

            foreach (int i in inputArr)
            {
                if (i < min)
                {
                    min = i;
                }
            }

            Console.WriteLine(min);
        }

        public static void CountUppercaseLetters(string inputStr)
        {
            int num = 0;
            foreach (char c in inputStr)
            {
                if (char.IsUpper(c))
                {
                    num++;
                }
            }

            Console.WriteLine(num);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            int[] ints = new int[10] { 5, 3, 20, 1, 4, 33, -22, 6, 4, 3 };
            myHelper.FindMinimum(ints);

            string str = "Show Me The Money";
            myHelper.CountUppercaseLetters(str);
        }
    }
}

 

 

 

심화 과제 3 ) 업적 시스템

새로운 cs 파일을 만들고, Achievement 클래스를 생성. 아래 구현 사항을 보다가 필요해보이는 내용이 발견되면 자유롭게 추가 구현

일반 필드 및 프로퍼티

  • string Name: 업적 이름
  • string Description: 업적 설명
  • int Goal: 목표 수치
  • int Progress: 현재 진행 수치 (기본값 0)
  • bool IsCompleted: 업적 달성 여부 (기본값 false)

static 필드

  • int TotalAchievements: 생성된 업적의 총 개수를 저장하는 static 필드
  • int CompletedAchievements: 달성된 업적의 총 개수를 저장하는 static 필드

생성자

  • 이름, 설명, 목표 수치를 받아 초기화
  • 생성자가 호출될 때마다 TotalAchievements를 증가.

메서드

  • AddProgress
    • 반환 없음. 인자값으로 int value를 받음
    • Progress에 value를 더하고 목표 수치에 도달했는지 확인
    • 목표를 달성하면:
      • IsCompleted를 true로 설정.
      • CompletedAchievements를 1 증가.
      • "업적 [업적 이름] 달성!" 출력.
  • DisplayInfo
    • 업적 이름, 설명, 목표 및 진행 상황, 달성 여부를 출력
    • 본인 취향껏
  • static 메서드: DisplaySummary
    • 반환 없음
    • 현재 생성된 업적의 총 개수와 달성된 업적의 총 개수를 출력
  • 테스트를 위해 메인으로 이동하여 다음을 작성
  • Achievement 객체를 3개 생성
    • 첫 번째 업적: "초급 도전자", "점수 100점 달성", 목표 100
    • 두 번째 업적: "중급 도전자", "점수 500점 달성", 목표 500
    • 세 번째 업적: "고급 도전자", "점수 1000점 달성", 목표 1000
  • 각 업적의 AddProgress 메서드를 호출하여 진행 상황을 업데이트:
    • 첫 번째 업적에 AddProgress 인자값으로 100
    • 두 번째 업적에 AddProgress 인자값으로 600
    • 세 번째 업적에 AddProgress 인자값으로 800
  • 각 업적의 DisplayInfo를 호출하여 현재 상태를 출력.
  • DisplaySummary를 호출하여 총 업적 및 달성된 업적 개수를 출력.

 

using System;

namespace StaticTask
{
    class Achievemnet
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public int Goal { get; set; }
        public int Progress { get; set; }
        public bool IsCompleted { get; set; }

        private static int TotalAchievements;
        private static int CompletedAchievements;

        public Achievemnet(string inputName, string inputDes, int inputGoal)
        {
            Name = inputName;
            Description = inputDes;
            Goal = inputGoal;

            TotalAchievements++;
        }

        public void AddProgress(int value)
        {
            Progress += value;
            if (Progress >= Goal)
            {
                IsCompleted = true;
                CompletedAchievements++;
                Console.WriteLine($"업적 {Name} 달성!");
            }
        }

        public void DisplayInfo()
        {
            Console.WriteLine("---------------------------");
            Console.Write($"업적명: {Name} ");
            Console.Write(IsCompleted ? "달성" : "미달성");
            Console.WriteLine();
            Console.WriteLine($"{Progress} / {Goal}");
            Console.WriteLine(Description);
            Console.WriteLine("---------------------------");
        }

        public static void DisplaySummary()
        {
            Console.WriteLine($"{CompletedAchievements} / {TotalAchievements}");
        }

    }
}

 

 

using System;

namespace StaticTask
{
    class Program
    {
        static void Main(string[] args)
        {
            Achievemnet ach1 = new Achievemnet("초급 도전자", "점수 100점 달성", 100);
            Achievemnet ach2 = new Achievemnet("중급 도전자", "점수 500점 달성", 500);
            Achievemnet ach3 = new Achievemnet("고급 도전자", "점수 1000점 달성", 1000);

            ach1.AddProgress(100);
            ach2.AddProgress(600);
            ach3.AddProgress(800);

            ach1.DisplayInfo();
            ach2.DisplayInfo();
            ach3.DisplayInfo();

            Console.WriteLine();
            Console.WriteLine("-------------------------------");
            Console.WriteLine();

            Achievemnet.DisplaySummary();
        }
    }
}

'C#' 카테고리의 다른 글

C# - 추상 클래스 (Abstract Class)  (0) 2025.09.21
C# - 오버로딩과 오버라이딩의 차이  (0) 2025.09.19
C# - 클래스 상속 (Inheritance)  (0) 2025.09.19
C# - 클래스와 Static  (0) 2025.09.18
C# - 클래스와 구조체의 차이  (0) 2025.09.17
'C#' 카테고리의 다른 글
  • C# - 추상 클래스 (Abstract Class)
  • C# - 오버로딩과 오버라이딩의 차이
  • C# - 클래스 상속 (Inheritance)
  • C# - 클래스와 Static
ellug
ellug
Web / App / Game Dev
  • ellug
    dev.ellug
    ellug
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • Javascript (React, Next) (1)
      • C# (66)
      • Graphics (1)
      • Unity (25)
      • 프로그래머스 (0)
        • Lv.0 (0)
        • Lv.1 (0)
        • Lv.2 (0)
        • Lv.3 (0)
      • AI Agent (0)
      • StableDiffusion (0)
      • ETC (1)
      • 잡담 (0)
      • 유머 (0)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    function
    Queue
    터미널
    list
    게임
    알고리즘
    unity
    콘솔
    네트워크
    유니티
    Abstract
    interface
    class
    C#
    Design Pattern
    stack
    struct
    console
    useState
    delegate
    Photon
    큐
    firebase
    클래스
    inputsystem
    추상 클래스
    스택
    Network
    자료구조
    최적화
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
ellug
C# - 클래스 Static 실습 문제 풀이
상단으로

티스토리툴바