Static modifier
Peponi │ 11/27/2024 │ 2m
C#
SyntaxKeywordModifier
Static modifier
11/27/2024
2m
Peponi
C#
SyntaxKeywordModifier
1. Introduction
static
한정자는 대상 인스턴스를 컴파일 타임에 확정한다. 런타임에는 인스턴스화가 불가능하며 인덱서, 소멸자 사용이 불가능하다.
static
한정자는 필드, 메서드, 속성 등에 사용 가능하며 형식 자체에 속하는 정적 멤버를 선언 가능케 한다. 따라서 유틸리티 기능 등을 정의하여 반복 사용하기 좋다.
C# 9버전부터는 람다 식, 무명 메서드에 static
을 사용할 수 있다.
2. Example
public static class Math
{
public static T Sum<T>(T value1, T value2) where T : struct
{
var sum = Convert.ToDouble(value1) + Convert.ToDouble(value2);
return (T)Convert.ChangeType(sum, typeof(T));
}
}
internal class Program
{
private static void Main()
{
var sum = Math.Sum(1, 2);
Console.WriteLine(sum); // 3
}
}
public class RPCServices
{
public string ServiceName { get; init; }
public static int ServiceCount = 0;
public RPCServices(string serviceName)
{
ServiceName = serviceName;
ServiceCount++;
}
public static void GetServiceCount() => Console.WriteLine(ServiceCount);
}
internal class Program
{
private static void Main()
{
var service1 = new RPCServices("service1");
var service2 = new RPCServices("service2");
RPCServices.GetServiceCount(); // 2
}
}