티스토리 뷰
const 대 readonly
비교
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Some s1 = new Some();
Console.WriteLine(Some.constField); // const : 항상 static
Console.WriteLine(s1.readonlyField1);
Console.WriteLine(s1.readonlyField2);
Some s2 = new Some(5);
Console.WriteLine(s2.readonlyField2);
}
}
class Some
{
// const readonly 공통 : 클래스 밖에서 값을 바꿀 수 없음
// const : 항상 static (static 키워드 쓰지 않음)
// const : 항상 선언시 초기화해야함
// const : 초기화하지 않으면 exception 발생
public const int constField = 2;
// readonly : 선언시 초기화 가능
// readonly : constructor 이용한 초기화 가능
// readonly : 초기화하지 않으면 0 값으로 초기화됨 (string 형은 null)
public readonly int readonlyField1 = 3;
public readonly int readonlyField2;
public Some()
{
readonlyField2 = 4;
}
public Some(int other)
{
readonlyField2 = other;
}
}
class Some2 : Some
{
public Some2(int other)
: base(other) // 가능
{
}
}
class Some3 : Some
{
public Some3()
{
readonlyField2 = 7; // error 발생
}
}
}
namespace Test
{
class Program
{
static void Main(string[] args)
{
Some s1 = new Some();
Console.WriteLine(Some.constField); // const : 항상 static
Console.WriteLine(s1.readonlyField1);
Console.WriteLine(s1.readonlyField2);
Some s2 = new Some(5);
Console.WriteLine(s2.readonlyField2);
}
}
class Some
{
// const readonly 공통 : 클래스 밖에서 값을 바꿀 수 없음
// const : 항상 static (static 키워드 쓰지 않음)
// const : 항상 선언시 초기화해야함
// const : 초기화하지 않으면 exception 발생
public const int constField = 2;
// readonly : 선언시 초기화 가능
// readonly : constructor 이용한 초기화 가능
// readonly : 초기화하지 않으면 0 값으로 초기화됨 (string 형은 null)
public readonly int readonlyField1 = 3;
public readonly int readonlyField2;
public Some()
{
readonlyField2 = 4;
}
public Some(int other)
{
readonlyField2 = other;
}
}
class Some2 : Some
{
public Some2(int other)
: base(other) // 가능
{
}
}
class Some3 : Some
{
public Some3()
{
readonlyField2 = 7; // error 발생
}
}
}
'Code > C#' 카테고리의 다른 글
[C#] Lambda Expression vs Anonymous Method (0) | 2008.02.11 |
---|---|
[C#] Extension Methods 사용법 (0) | 2008.02.11 |
PInvoke SetForegroundWindow Sample Code (0) | 2008.01.14 |
Process Class Sample Code 1 (0) | 2008.01.14 |
GenericDictionaryXmlSerializer 클래스 2 사용 예제 (0) | 2007.12.16 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- AdSense감추기
- Sample Code
- download.com
- registry
- AxWebBrowser
- READYSTATE_COMPLETE
- 애드센스감추기
- Microsoft
- Rollback Rx
- ScreenHunter
- Regular Expressions
- autohotkey
- 유틸리티
- DotNetMagic
- Phalanger
- 스크린캡쳐
- tagREADYSTATE
- AdSense숨기기
- WinAutomation
- windows
- java
- Automation
- jre
- c#
- .net framework
- 애드센스숨기기
- iTextSharp
- Service pack
- iText
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함