다음과 같은 코드가 있다고 가정하자:
TextBlock newTextBlock = new TextBlock();
newTextBlock.Text = string.Format("{0} 번 터치되었습니다.", touched);
newTextBlock.HorizontalAlignment = HorizontalAlignment.Left;
newTextBlock.VerticalAlignment = VerticalAlignment.Top;
newTextBlock.Margin = new Thickness(
0,
2 * touched * txtblXAML.ActualHeight,
0, 0);
위 코드는 다음과 같이 바꿀 수 있다:
TextBlock newTextBlock = new TextBlock()
{
Text = string.Format("{0} 번 터치되었습니다.", touched),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(
0,
touched * txtblXAML.ActualHeight,
0, 0)
};
위 문법은 C# 3.0부터 포함된 객체 이니셜라이저(Object Initializer) 문법으로, 명시적인 생성자 없이도 객체의 내부 멤버의 값을 지정할 수 있는 방법을 제공한다. 객체 이니셜라이저를 사용하면 파라메터를 통해 내부 변수의 값을 정의하는 코드를 작성하는 수고를 덜 수 있으며, 특정 객체를 생성할 때 해당 객체와 관련된 코드가 시각적으로 분리되어 있어 코드를 읽기가 용이하다.
'TechLog' 카테고리의 다른 글
| 윈도우 폰 7 개발자 도구 7.1 베타 (망고 업데이트) 설치 후 프로그램 디버깅이 안 될 경우 (0) | 2011.06.13 |
|---|---|
| WP7 앱에서 가로/세로 방향 지원하기 (0) | 2011.06.13 |
| WP 앱 설정 저장하기 (0) | 2011.05.22 |
| WP 실버라이트 앱의 Margin, Border, Padding (0) | 2011.05.21 |
| Xcode에서 탭키에 강제 들여쓰기 기능 할당하기 (0) | 2011.05.16 |