19 static

vencott·2021년 6월 2일
0

C#

목록 보기
19/32

static 메서드

인스턴스 메서드와는 달리 직접 [클래스명.메서드명] 형식으로 호출

static 메서드는 인스턴스 객체로부터 호출될 수 없다

public class MyClass
{
   private int val = 1;
   
   // 인스턴스 메서드
   public int InstRun()
   {
      return val;
   }
   
   // 정적 메서드
   public static int Run() 
   {
      return 1;
   }
}

public class Client
{
   public void Test()
   {
      // 인스턴스 메서드 호출
      MyClass myClass = new MyClass();
      int i = myClass.InstRun();

      // 정적 메서드 호출
      int j = MyClass.Run();
   }
}

static 필드

non-static 필드는 인스턴스를 생성할 때 마다 메모리에 매번 새로 생성

static 필드는 프로그램 실행 후 해당 클래스가 처음으로 사용될 때 한번 초기화되어 계속 동일한 메모리를 사용

// static 필드
protected static int _id;

// static 속성
public static string Name { get; set; }

static 클래스

모든 클래스 멤버가 static으로 되어있으며, 클래스명 앞에 static을 명시

일반 생성자는 가질 수 없지만(인스턴스 생성이 불가능하므로) static 생성자를 통해 필드들을 초기화 하는데 사용할 수 있다

public static class MyUtility
{
   private static int ver;

   // static 생성자
   static MyUtility()
   { 
      ver = 1;
   }

   public static string Convert(int i)
   {
      return i.ToString();
   }

   public static int ConvertBack(string s)
   {
      return int.Parse(s);
   }
}

static void Main(string[] args)
{
   string str = MyUtility.Convert(123);
   int i = MyUtility.ConvertBack(str);
}

출처: http://www.csharpstudy.com/

profile
Backend Developer

0개의 댓글