■ 정적 클래스(Static Class) :
- 기본적으로 비정적 클래스(Non-Static)와 동일하지만, 정적 클래스(Static)는 인스턴스화 할 수 없다.
- new 연산자를 사용하여 변수를 만들 수 없음
- 모든 클래스 멤버가 static 멤버로 되어 있음
- 특정 인스턴트에 고유한 데이터를 저장하거나 검색할 필요가 없을 때 사용
■ Example
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"StaticClass.x = {StaticClass.x}");
StaticClass.StaticTest(20);
}
}
static class StaticClass
{
public static int x = 10;
public static void StaticTest(int y)
{
Console.WriteLine($"y = {y}, 정적(static) 메서드입니다.");
}
}
■ 정적 필드(Static Field), 정적 메서드(Static Method) :
- 인스턴스를 생성하지 않은 경우에도 클래스를 호출할 수 있음
- 인스턴스의 이름이 아닌 클래스 이름으로 호출
- 모든 인스턴스가 공유
- 일반적으로 정적 클래스(static class)를 사용하는 것보다 일부 정적 필드(static field), 정적 메서드(static method)를 포함하는 비정적 클래스(Non-static class)를 사용
- 정적 메서드(static method) 내부에서 클래스의 인스턴스 객체 멤버를 참조해서는 안됨
- Non-static 필드들은 클래스 인스턴스를 생성할 때마다 메모리 생성
- Static 필드는 프로그램 실행 후 해당 클래스가 처음 사용될 때 한번 초기화되어 계속 동일한 메모리 사용
■ Exmaple
class Program
{
static void Main(string[] args)
{
TestClass test01 = new TestClass();
Console.WriteLine($"X = {TestClass.X}, Y = {test01.Y}");
TestClass test02 = new TestClass();
Console.WriteLine($"X = {TestClass.X}, Y = {test02.Y}");
TestClass test03 = new TestClass();
Console.WriteLine($"X = {TestClass.X}, Y = {test03.Y}");
}
}
class TestClass
{
public static int X = 10; // 정적 필드
public int Y = 20; // 인스턴스 필드
public TestClass()
{
X++;
Y++;
}
}
'개인공부 > C#' 카테고리의 다른 글
[C#] 상속(Inheritance) (0) | 2022.09.07 |
---|---|
[C#] 접근 제한자(Access Modifier) (0) | 2022.09.06 |
[C#] 얕은 복사(Shallow Copy), 깊은 복사(Deep Copy) (0) | 2022.09.05 |
[C#] 클래스(Class) (0) | 2022.09.01 |
[C#] Call by Value, Call by Reference (0) | 2022.08.31 |