C#) static이란? - chatgpt

jiyul·2023년 11월 13일
0

C#

목록 보기
6/21

C#에서 static은 클래스의 인스턴스가 아닌 클래스 자체에 속하는 멤버를 나타내는 키워드입니다. static 멤버는 클래스의 모든 인스턴스에 공통적으로 사용되며, 특정 인스턴스에 속하는 것이 아니라 클래스 자체에 속하게 됩니다.

다음은 C#에서 static이 사용되는 몇 가지 경우입니다:

  1. Static 메서드:

    public class Calculator
    {
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
    
    // 사용 예시
    int sum = Calculator.Add(3, 5);

    Add 메서드는 Calculator 클래스의 인스턴스를 생성하지 않고 직접 호출할 수 있습니다.

  2. Static 속성:

    public class Configuration
    {
        private static string _apiKey;
    
        public static string ApiKey
        {
            get { return _apiKey; }
            set { _apiKey = value; }
        }
    }
    
    // 사용 예시
    Configuration.ApiKey = "my_api_key";

    ApiKey 속성은 클래스 자체에 속하며, 인스턴스를 만들지 않고도 접근할 수 있습니다.

  3. Static 필드:

    public class Counter
    {
        private static int _count;
    
        public static int GetCount()
        {
            return _count;
        }
    
        public static void Increment()
        {
            _count++;
        }
    }
    
    // 사용 예시
    Counter.Increment();
    int currentCount = Counter.GetCount();

    _count 필드는 클래스의 모든 인스턴스에서 공유되며, IncrementGetCount 메서드를 통해 조작됩니다.

static 멤버는 해당 클래스의 인스턴스를 생성하지 않고도 사용할 수 있기 때문에, 유틸리티 메서드, 공유 자원에 대한 접근 등 다양한 상황에서 활용됩니다.

profile
Let's take the lead

0개의 댓글

관련 채용 정보