Programming/C#

[C# 프로그래밍] 13장 애트리뷰트

Hyunseok Oh 2016. 1. 11. 02:14

애트리뷰트 생성 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
 
[System.AttributeUsage(System.AttributeTargets.Class |
                       System.AttributeTargets.Struct, AllowMultiple = true)]
public class Author : System.Attribute
{
    public string Name { get; set; }
    public double Version { get; set; }
    public Author(string name)
    {
        Name = name;
        Version = 1.0;
    }
}
 
namespace EX13_Attribute
{
    [Author("Admin", Version = 1.5)]
    [Author("Hyunseok Oh", Version = 1.1)]
    class Enemy
    {
    }
 
    class MainClass
    {
        public static void Main (string[] args)
        {
            Enemy enemy = new Enemy ();
            object[] attrs = enemy.GetType ().GetCustomAttributes (true);
            foreach (Author attr in attrs)
            {
                Console.WriteLine("Class {0} Version {1} made by {2} ",
                                                              enemy.GetType().Name,
                                                              ((Author)attr).Version,
                                                              ((Author)attr).Name);
            }
        }
    }
}
cs