이 페이지에서는 한정자 키워드를 static
다룹니다.
static
키워드도 지시문의 using static
일부입니다.
static
한정자를 사용하여 특정 개체가 아닌 형식 자체에 속하는 정적 멤버를 선언합니다.
static
수정자를 사용하여 static
클래스를 선언할 수 있습니다. 클래스, 인터페이스 및 구조체에서 필드, 메서드, 속성, 연산자, 이벤트 및 생성자에 한정자를 추가할 static
수 있습니다.
static
수정자는 인덱서 또는 종결자와 함께 사용할 수 없습니다. 자세한 내용은 static 클래스 및 static 클래스 멤버를 참조하세요.
로컬 함수에 static
한정자를 추가할 수 있습니다. 정적 로컬 함수는 지역 변수 또는 인스턴스 상태를 캡처할 수 없습니다.
class Calc1
{
public void CalculateSum()
{
int a = 3;
int b = 7;
// Static local function - cannot access 'a' or 'b' directly
static int Add(int x, int y)
{
return x + y;
}
int result = Add(a, b);
Console.WriteLine($"Sum: {result}");
}
}
/*
Output:
Sum: 10
*/
람다 식 또는 무명 메서드에 한정자를 추가할 static
수 있습니다. 정적 람다 또는 무명 메서드는 지역 변수 또는 인스턴스 상태를 캡처할 수 없습니다.
class Calc2
{
static void Main()
{
Func<int, int, int> add = static (a, b) => a + b;
int result = add(5, 10);
Console.WriteLine($"Sum: {result}");
}
}
/*
Output:
Sum: 15
*/
예제 - 정적 클래스
다음 클래스는 static
로 선언되어 있으며, static
메서드만 포함합니다.
static class CompanyEmployee
{
public static void DoSomething() { /*...*/ }
public static void DoSomethingElse() { /*...*/ }
}
상수 또는 형식 선언은 암시적으로 멤버입니다 static
.
static
멤버는 인스턴스를 통해 참조할 수 없습니다. 대신 형식 이름을 통해 참조됩니다. 예를 들어 다음 클래스를 고려합니다.
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;
}
}
멤버 static
를 참조하려면, 멤버 x
에 동일한 범위에서 접근할 수 있는 경우가 아니라면, 정규화된 이름인 MyBaseC.MyStruct.x
을(를) 사용하십시오.
Console.WriteLine(MyBaseC.MyStruct.x);
클래스의 인스턴스에는 클래스의 모든 인스턴스 필드의 별도 복사본이 포함되어 있지만 각 static
필드의 복사본은 하나뿐입니다. 제네릭 형식의 경우 닫힌 각 제네릭 형식에는 고유한 정적 필드 복사본이 있습니다. 스레드당 하나의 복사본이 있는 ThreadStaticAttribute 것으로 표시된 정적 필드입니다.
this
을(를) 사용하여 static
메서드나 속성 접근자를 참조할 수 없습니다.
키워드가 static
클래스에 적용되는 경우 클래스의 모든 멤버는 이어야 static
합니다.
클래스, 인터페이스 및 static
클래스에는 생성자가 있을 static
수 있습니다.
static
생성자는 프로그램이 시작되고 클래스가 인스턴스화되는 시점 사이에 호출됩니다.
비고
키워드의 static
용도는 C++보다 더 제한적입니다. C++ 키워드와 비교하려면 Storage 클래스(C++)를 참조하세요.
구성원을 설명하기 위해, 회사 직원을 대표하는 클래스를 고려합니다. 클래스에 직원 수를 계산하는 메서드와 직원 수를 저장할 필드가 포함되어 있다고 가정합니다. 메서드와 필드가 모두 하나의 직원 인스턴스에 속하지 않습니다. 대신, 그들은 전체 직원의 클래스에 속한다. 클래스의 멤버로 static
선언해야 합니다.
예제 - 정적 필드 및 메서드
다음은 새 직원의 이름과 ID를 읽고, 직원 카운터를 하나씩 증가시키고, 새 직원의 정보와 새 직원 수를 표시하는 예제입니다. 이 프로그램은 키보드에서 현재 직원 수를 읽습니다.
public class Employee4
{
public string id;
public string name;
public Employee4()
{
}
public Employee4(string name, string id)
{
this.name = name;
this.id = id;
}
public static int employeeCounter;
public static int AddEmployee()
{
return ++employeeCounter;
}
}
class MainClass : Employee4
{
static void Main()
{
Console.Write("Enter the employee's name: ");
string name = Console.ReadLine();
Console.Write("Enter the employee's ID: ");
string id = Console.ReadLine();
// Create and configure the employee object.
Employee4 e = new Employee4(name, id);
Console.Write("Enter the current number of employees: ");
string n = Console.ReadLine();
Employee4.employeeCounter = Int32.Parse(n);
Employee4.AddEmployee();
// Display the new information.
Console.WriteLine($"Name: {e.name}");
Console.WriteLine($"ID: {e.id}");
Console.WriteLine($"New Number of Employees: {Employee4.employeeCounter}");
}
}
/*
Input:
Matthias Berndt
AF643G
15
*
Sample Output:
Enter the employee's name: Matthias Berndt
Enter the employee's ID: AF643G
Enter the current number of employees: 15
Name: Matthias Berndt
ID: AF643G
New Number of Employees: 16
*/
예제 - 정적 초기화
이 예제에서는 아직 선언되지 않은 다른 static
필드를 사용하여 필드를 초기화 static
할 수 있음을 보여줍니다. 필드에 값을 static
명시적으로 할당할 때까지 결과가 정의되지 않습니다.
class Test
{
static int x = y;
static int y = 5;
static void Main()
{
Console.WriteLine(Test.x);
Console.WriteLine(Test.y);
Test.x = 99;
Console.WriteLine(Test.x);
}
}
/*
Output:
0
5
99
*/
C# 언어 사양
자세한 내용은 C# 언어 사양을 참조하세요. 언어 사양은 C# 구문 및 사용의 최종 소스입니다.
참고하십시오
.NET