ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1067)
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (180)
      • Unreal (69)
      • Unity (100)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 백준
  • C
  • 문자열
  • 포인터
  • string
  • 파이썬
  • 배열
  • 티스토리챌린지
  • 클래스
  • SQL
  • 프로그래머스
  • c#
  • 알고리즘
  • 함수
  • Unity
  • 오블완
  • 그래픽스
  • C++
  • 언리얼
  • 유니티

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

프로그래밍 언어/C#

C# 리플렉션과 어트리뷰트 (Reflection and Attributes)

2022. 7. 8. 14:51

리플렉션

C#에서는 프로그램 실행 도중에 객체의 정보를 조사하거나, 다른 모듈에 선언된 인스턴스를 생성하거나, 기존 개체에서 형식을 가져오고 해당하는 메소드를 호출, 또는 해당 필드와 속성에 접근할 수 있는 기능이다.

형식  메소드  설명 
Type GetType() 지정된 형식의 Type 개체를 가져온다. 
MemberInfo[] GetMembers()  해당 형식의 멤버 목록을 가져온다.
MethodInfo[] GetMethods()  해당 형식의 메소드 목록을 가져온다.
FieldInfo[] GetFields()  해당 형식의 필드 목록을 가져온다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;

namespace ConsoleApplication43
{
    class Animal
    {
        public int age;
        public string name;

        public Animal(string name, int age)
        {
            this.age = age;
            this.name = name;
        }
        public void eat()
        {
            Console.WriteLine("먹는다!");
        }
        public void sleep()
        {
            Console.WriteLine("잔다!");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Animal animal = new Animal("고양이", 4);
            Type type = animal.GetType();

            ConstructorInfo[] coninfo = type.GetConstructors();
            Console.Write("생성자(Constructor) : ");
            foreach (ConstructorInfo tmp in coninfo)
                Console.WriteLine("\t{0}", tmp);
            Console.WriteLine();

            MemberInfo[] meminfo = type.GetMethods();
            Console.Write("메소드(Method) : ");
            foreach (MethodInfo tmp in meminfo)
                Console.Write("\t{0}", tmp);
            Console.WriteLine();

            FieldInfo[] fieldinfo = type.GetFields();
            Console.Write("필드(Field) : ");
            foreach (FieldInfo tmp in fieldinfo)
                Console.Write("\t{0}", tmp);
            Console.WriteLine();
        }
    }
}

어트리뷰트 (Attribute)

애트리뷰트는 클래스에 메타데이터를 추가할수 있는 기능이다. 주석과는 달리 클래스부터 시작해서 메소드, 구조체, 생성자, 프로퍼티, 필드, 이벤트, 인터페이스 등 여러가지 요소에 애트리뷰트를 사용할 수 있다.  

[attribute명(positional_parameter, name_parameter = value, ...)]
#define TEST

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;

namespace ConsoleApplication43
{
    class Program
    {
        // TEST가 정의되어 있어야만 호출이 가능합니다.
        [Conditional("TEST")]
        public void TestConditional()
        {
            Console.WriteLine("TestConditional!");
        }

        static void Main(string[] args)
        {
            Program program = new Program();

            program.TestConditional();
        }
    }
}

사용자 정의 어트리뷰트

커스텀 어트리뷰트는, 사용자가 직접 정의하는 어트리뷰트이다. 방금 말한 MSDN 링크에 들어가보시면, 모든 어트리뷰트는 System.Attribute 클래스에서 파생되었다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication43
{
    [CustomAttribute("STR", vartmp="TMP")]
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("CustomAttribute!");
        }
    }

    class CustomAttribute : System.Attribute
    {
        private string str;
        private string tmp;

        public CustomAttribute(string str)
        {
            this.str = str;
        }

        public string vartmp
        {
            get
            {
                return tmp;
            }
            set
            {
                tmp = value;
            }
        }
    }
}

그리고, Conditional 특성처럼, System.AttributeUsage를 이용하여, 적용 가능한 요소값을 지정할 수 있다. 아래는 코드 요소를 모두 나열한 것이다.

 

<VaildOn>



AttributeTargets


설명
All 모든 요소 
Assembly  어셈블리 
Module  모듈 
Inferface  인터페이스 
Class  클래스 
Struct  구조체 
Enum  열거형 
Constructor  생성자 
Method  메소드 
Property  프로퍼티 
Field  필드 
Event  이벤트 
Parameter  메소드의 매개 변수 
Delegate 델리게이트 
ReturnValue  메소드의 반환 값 

 

출처 : https://blog.hexabrain.net/152

저작자표시 (새창열림)

'프로그래밍 언어 > C#' 카테고리의 다른 글

C# 인덱서 (Indexer)  (0) 2022.07.19
C# 확장 메서드 (Extension Method)  (0) 2022.07.18
C# 전처리기의 모든것  (0) 2022.07.04
C# Action/Func/Predicate  (0) 2022.07.04
C# 배열 복사 방법  (0) 2022.07.01
    '프로그래밍 언어/C#' 카테고리의 다른 글
    • C# 인덱서 (Indexer)
    • C# 확장 메서드 (Extension Method)
    • C# 전처리기의 모든것
    • C# Action/Func/Predicate
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바