C#

77.C# - Attribute 사용자 정의 특성

Godffs 2009. 8. 18. 20:39
반응형

사용자 지정 특성에 대한 기본 클래스를 나타냅니다.
msdn에 있는 예제입니다.


Program.cs
01   using System;
02   namespace 사용자정의특성
03   {
04       [AttributeUsage( AttributeTargets.Method |
05    AttributeTargets.Property |AttributeTargets.Class,AllowMultiple=true)]
06  
07       public class AuthorAttrubite : Attribute //작성자 정보를 저장 하는 특성
08       {
09           //private string name; //필드
10           public string name; //사용자정의 특성을 불러오기 위해 name을
11                                           private에서 public로 변경
12  
13           public AuthorAttrubite(string name) //매개변수가 있는 생성자 생성
14           { this.name = name; }
15       }
16  
17       [AuthorAttrubite("이준철")] //사용자 정보를 불러오기
18  
19       class 사용자정의특성
20       {
21           static void Main(string[] args)
22           {
23               Say();
24  
25               //특성 정보 읽어오기
26               ShowMetaData();
27           }           
28              public static void Say() { Console.WriteLine("안녕하세요."); }
29  
30              //특성정보 읽어오기
31             private static void ShowMetaData()
32             {
33                 System.Attribute[] attrs =
34                System.Attribute.GetCustomAttributes(typeof(사용자정의특성));
35                 foreach (var attr in attrs)
36                 {
37                     AuthorAttrubite aa = attr as AuthorAttrubite;
38                     if (aa != null) {
39                         Console.WriteLine("{0}",aa.name); }
40                 }
41             }
42      }
43  }

4~5번라인 : 내장된 특성(여러개 정의 가능) 메소드와 프로퍼티드에 정의
                 AllowMultipe=true 는 다중사용 가능하게 표시
5번라인 : Class는 사용자정의특성을 불러오기 위해 추가
37~39라인 :as를 is로 바꾸면
                               if (attr is AuthorAttrubite)
                               {
                                   AuthorAttrubite aa = (AuthorAttrubite)attr;
                                   Console.WriteLine("{0}",aa.name);
                               }


결과화면


77.AttributeUser.zip
다운로드

반응형