보면 항상 궁금 했던 부분이였다. 클래스의 선언전에 [] 안에 넣는 것들은 무엇에 쓰고 왜쓰이나? 그리고 단어도 길어서 항상 어려워 보였다.
소스
using System;
using System.Reflection;
public class AppleAttribute : Attribute
{
private string msg;
public AppleAttribute(string msg)
{
this.msg = msg;
}
public string GetMsg()
{
return this.msg;
}
}
[AppleAttribute("사과를 위한 클래스입니다.")]
public class AppleStore
{
[AppleAttribute("사과의 개수 나타내는 필드입니다.")]
public int count = 5;
[AppleAttribute("사과의 개수를 리턴하는 필드입니다.")]
public int GetCount()
{
return this.count;
}
}
public class AppleAttrInfoTest
{
public static void Main()
{
Type type = Type.GetType("AppleStore");
foreach(Attribute attr in type.GetCustomAttributes(true))
{
AppleAttribute aat = attr as AppleAttribute;
if(null != aat)
{
Console.WriteLine(aat.GetMsg());
}
}
foreach(FieldInfo finfo in type.GetFields())
{
foreach(Attribute attr in finfo.GetCustomAttributes(true))
{
AppleAttribute aat = attr as AppleAttribute;
Console.WriteLine(aat.GetMsg());
}
}
foreach(MethodInfo minfo in type.GetMethods())
{
foreach(Attribute attr in minfo.GetCustomAttributes(true))
{
AppleAttribute aat = attr as AppleAttribute;
Console.WriteLine(aat.GetMsg());
}
}
}
}
결과
사과를 위한 클래스입니다.
사과의 개수 나타내는 필드입니다.
사과의 개수를 리턴하는 필드입니다.
위 속성을 사용하는 이유는 컴파일시 또는 실행시에 그 정보를 이용하기 위해서이다.
소스
#define JABOOK
using System;
using System.Diagnostics;
class ConditionalTest
{
[Conditional("JABOOK")]
public static void DefineMethod()
{
Console.WriteLine("Define Conditional Attribute!!");
}
[Conditional("MICROSOFT")]
public static void UndefineMethod()
{
Console.WriteLine("Undefine Conditional Attribute!!");
}
public static void Main()
{
ConditionalTest.DefineMethod();
ConditionalTest.UndefineMethod();
}
}
결과
Define Conditional Attribute!!
위의 결과에서 봤듯이 define이 된 것만 실행되어서 실행을 컨트롤 할수 있다.
소스
using System;
class ObsoleteTest
{
[Obsolete("지금 Obsolete 로 선언된 메서드를 사용하였습니다.")]
public static void ObsoMethod()
{
Console.WriteLine("Obsolete Attribute Method!!");
}
public static void NormMethod()
{
Console.WriteLine("Normal Method!!");
}
public static void Main()
{
ObsoleteTest.ObsoMethod();
ObsoleteTest.NormMethod();
}
}
결과
ObsoleteTest.cs(17,3): warning CS0618: 'ObsoleteTest.ObsoMethod()'은(는) 사용되지 않습니다. '지금 Obsolete 로 선언된 메서드를 사용하였습니다.'
C:\Documents and Settings\CAN01\My Documents>ObsoleteTest
Obsolete Attribute Method!!
Normal Method!!
프로그램의 어셈블리를 업그레이드 했을시 기존에 사용하던 기능을 사용하지 말라고 경고 메세지를 보낼때 사용하면 좋겠다.
소스
using System;
using System.Runtime.InteropServices;
class DLLImport
{
[DllImport("User32.dll")]
public static extern int MessageBox(int i,string text,string title,int type);
public static void Main()
{
MessageBox(0,"MessageBox Test","DllImport Test",2);
}
}
결과
기존에 만들어진 dll 을 사용하려고 할때는 이 속성을 이요하면 되겠다.
댓글을 달아 주세요