Attribute가 런타임에게 특정 작업을 지시한다? 도대체 무슨 말일까요? 한번 보도록 하죠.
MSDN을 보니 PropertyGrid를 생성하는 예제가 있군요.
소스는 귀찮아서 때려 붙이고 옆에 주석을 달겠습니다.
[DefaultPropertyAttribute("SaveOnClose")] // Attribute 등장!! 기본으로 선택되어 있을 Property를 설정합니다.
public class AppSettings
{ // 아래로 각종 변수 초기화
private bool saveOnClose = true;
private string greetingText = "Welcome to your application!";
private int itemsInMRU = 4;
private int maxRepeatRate = 10;
private bool settingsChanged = false;
private string appVersion = "1.0";
private Size windowSize = new Size(100, 100);
private Font windowFont = new Font("Arial", 8, FontStyle.Regular);
private Color toolbarColor = SystemColors.Control;
[CategoryAttribute("Document Settings"),
DefaultValueAttribute(true)] // 그렇습니다. Attribute는 단순 주석이 아니었던 것이죠. 카테고리를 나눠주는거였군요.
public bool SaveOnClose // SaveOnClose 항목이 Document Settings 카테고리 밑으로 들어갑니다.
{
get { return saveOnClose; }
set { saveOnClose = value; }
}
[CategoryAttribute("Document Settings")]
public Size WindowSize
{
get { return windowSize; }
set { windowSize = value; }
}
[CategoryAttribute("Document Settings")]
public Font WindowFont
{
get { return windowFont; }
set { windowFont = value; }
}
[CategoryAttribute("Global Settings")] // Global Settings 카테고리로 넣습니다.
public Color ToolbarColor
{
get { return toolbarColor; }
set { toolbarColor = value; }
}
[CategoryAttribute("Global Settings"),
ReadOnlyAttribute(true), // !!! ReadOnly까지 설정되는군요.
DefaultValueAttribute("Welcome to your application!")] // 기본값 설정에...
public string GreetingText
{
get { return greetingText; }
set { greetingText = value; }
}
[CategoryAttribute("Global Settings"),
DefaultValueAttribute(4)]
public int ItemsInMRUList
{
get { return itemsInMRU; }
set { itemsInMRU = value; }
}
[DescriptionAttribute("The rate in milliseconds that the text will repeat."), // Property창 아래 설명문까지...
CategoryAttribute("Global Settings"),
DefaultValueAttribute(10)]
public int MaxRepeatRate
{
get { return maxRepeatRate; }
set { maxRepeatRate = value; }
}
[BrowsableAttribute(false), // false하면 사라집니다.
DefaultValueAttribute(false)]
public bool SettingsChanged
{
get { return settingsChanged; }
set { settingsChanged = value; }
}
[CategoryAttribute("Version"),
DefaultValueAttribute("1.0"),
ReadOnlyAttribute(true)]
public string AppVersion
{
get { return appVersion; }
set { appVersion = value; }
}
}
위의 소스를 보면 대충 감이 잡힐겁니다.. 어떻게 사용하는지... 장황했지만 별 거 없습니다. 한마디로 Attribute는 프로그램에 필요한 정보를 첨가시켜 놓을 수있는 것입니다. 컴파일 타임과 런타임에 모두 영향을 줄 수 있고, 어셈블리에 메타데이터 형식으로 저장된다고 하네요.
어려워 보였지만 막상 프로그램을 짜보니 그닥 어렵진 않다는 것을 알 수 있었습니다.
기본적은 내장 Attribute는 Conditional과 Obsolete, DllImport가 있다고 하는데 이것에 관한 것은 좀 더 공부를 하고 빠른 시일내에 다시 글을 써 보도록 하죠.
'Development > C#' 카테고리의 다른 글
TextBox에 숫자만 입력받기 (0) | 2011.04.29 |
---|---|
코드로 배포/설치프로그램 생성 후 명령프롬프트 명령 내리기 (0) | 2011.02.16 |
Attribute 사용처 (0) | 2010.03.08 |
다른 프로세스에서 사용 중인 파일 읽어오기. (2) | 2010.03.08 |
Binary 파일에서 문자열 읽어오는 방법 (0) | 2010.03.08 |