2013. 12. 29. 16:11
const int x = 0; public const double gravitationalConstant = 6.673e-11; private const string productName = "Visual C#";
상수 선언에서는 다음과 같이 여러 개의 상수를 선언할 수 있습니다.
public const double x = 1.0, y = 2.0, z = 3.0;
static 한정자는 상수 선언에 사용할 수 없습니다.
상수 식에는 다음과 같이 상수를 사용할 수 있습니다.
public const int c1 = 5; public const int c2 = c1 + 100;
![]() |
---|
readonly 키워드는 const 키워드와 다릅니다. const 필드는 필드를 선언할 때만 초기화될 수 있습니다. readonly 필드는 필드를 선언할 때 또는 생성자에서 초기화될 수 있습니다. 따라서 readonly 필드의 값은 사용된 생성자에 따라 다릅니다. 또한 const 필드는 컴파일 타임 상수인 반면 readonly 필드는 런타임 상수로도 사용할 수 있습니다(예: public static readonly uint l1 = (uint)DateTime.Now.Ticks;). |
public class ConstTest { class SampleClass { public int x; public int y; public const int c1 = 5; public const int c2 = c1 + 5; public SampleClass(int p1, int p2) { x = p1; y = p2; } } static void Main() { SampleClass mC = new SampleClass(11, 22); Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); Console.WriteLine("c1 = {0}, c2 = {1}", SampleClass.c1, SampleClass.c2 ); } } /* Output x = 11, y = 22 c1 = 5, c2 = 10 */
다음 예제에서는 상수를 지역 변수로 사용하는 방법을 보여 줍니다.
public class SealedTest { static void Main() { const int c = 707; Console.WriteLine("My local constant = {0}", c); } } // Output: My local constant = 707
'게임개발공부 > C#공부' 카테고리의 다른 글
추상 클래스 봉인 클래스 (0) | 2013.12.29 |
---|---|
인터페이스 (0) | 2013.12.29 |
c#에서의 다형성 (0) | 2013.12.27 |
제네릭(generic), 함수, 변수 개념. (0) | 2013.12.27 |
속성(property) (0) | 2013.12.27 |