static 클래스의 기능

static 클래스의 기능을 간단히 정의하면, static 멤버를 담을 수 있는 ‘컨테이너’의 역할을 한다.

[컨테이너 - 예시 코드]

using System;
using static System.Console; // 추가

namespace StaticClass
{
	static class Calculator // 컨테이너 기능
	{
		public static double add(double a, double b)
		{
			return a + b;
		}

		public static double mul(double a, double b)
		{
			return a * b;
		}

		public static double power(double a)
		{
			return a * a;
		}
	}

	internal class Program
	{
		static void Main(string[] args)
		{
			WriteLine(Calculator.add(5, 2.5));
			WriteLine(Calculator.mul(5, 2.5));
			WriteLine(Calculator.power(5));
		}
	}
}

대표적인 내장 static 클래스

  • Console: WriteLine, ReadLine, ReadKey 등의 메소드 지원, 콘솔 윈도우와 소통하는 역할.
  • Math: 계산에 필요한 연산 로직, 상수 등을 제공.
  • Environment: 프로그램이 작동하는 환경에 관한 정보(OS 버전, 디렉토리, 유저명 등)를 제공.

static 클래스의 규칙

  • static 클래스는 static 멤버만을 가질 수 있다.
  • static 클래스는 인스턴스화할 수 없다.
  • static 클래스는 selaed 되어져 있다.
  • static 클래스는 consturctor를 가질 수 없다. (단, static constructor를 가질 수 있음)
  • static 클래스에서는 this 를 사용할 수 없다. (this 는 현재 인스턴스를 지칭하는 키워드)

[static constructor - 예시 코드]

using System;

namespace StaticClass
{
	static class SystemMonitor
	{
		private static readonly DateTime _startTime;
		
		static SystemMonitor() // static constructor
		{
			_startTime = DateTime.UtcNow;
		}

		public static string Report()
		{
			return $"{(DateTime.UtcNow - _startTime).TotalSeconds} seconds";
		}
	}
}

static constructor 주의사항

  • 매개 변수를 가질 수 없음.
  • 접근 제어자를 가질 수 없음.
  • 상속되거나 오버로드할 수 없음.
  • directory로 콜할 수 없음. (CLR에 의해 static class부터 첫번째로 호출 되어짐.)

태그: ,

카테고리:

업데이트:

댓글남기기