.NET프로그래밍/C# 3.5 SP1

78. 특성(Attribute)

holland14 2009. 8. 18. 11:50


==> 특성.cs



using System;

public class 특성 // 모든 특성은 클래스이다. 뒤에붙는 Attribute접미사는 생략가능하다.
{
    public static void Main()
    {
        Say1();
        Say2();
    }

    /// <summary>
    /// 닷넷 1.0 버전
    /// </summary>
    [Obsolete("현재 메서드는 오래된 버전이므로, Say2()를 사용하세요.", false)] // false로 하면 실행되고 경고만 뜨지만, true로 하면 실행되지 않는다. 
    public static void Say1()
    {
        Console.WriteLine("안녕");
    }

    /// <summary>
    ///  닷넷 2.0 버전 이상
    /// </summary>
    public static void Say2()
    {
        Console.WriteLine("안녕하세요");
    }
}



==============================================================================================




==> 사용자정의특성.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 사용자정의특성
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=true)] // Method와 Class에 특성을 주고 다중사용 가능하게 한다.
    public class AuthorAttribute : Attribute // 작성자 정보를 담아놓을 수 있는 간단한 특성
    {
        public string name; // 이름의 정보를 담아놓을(보관) 수 있는 그릇 하나. 여기서는 필드를 public으로 선언했다.
        public AuthorAttribute(string name)
        {
            this.name = name;
        }
    }
    [AuthorAttribute("RedPlus")]
    class 사용자정의특성
    {
        static void Main(string[] args)
        {
            Say();

            ShowMetaData();
        }

        // 특성정보 읽어오기
        private static void ShowMetaData()
        {
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(사용자정의특성));
            foreach (var attr in attrs)
            {
                //if (attr is AuthorAttribute)
                //{
                //    AuthorAttribute aa =(AuthorAttribute)attr;
                //    Console.WriteLine("{0}", aa.name);
                //}
                AuthorAttribute aa = attr as AuthorAttribute;
                if (aa != null)
                {
                    Console.WriteLine("{0}", aa.name);
                }
            }
        }
        static void Say() { Console.WriteLine("안녕하세요."); }
    }
}