📕리플렉션(Reflection)
📖리플렉션이란?
리플렉션이란 C#에서 런타임 중에 객체의 메타 정보를 확인하고 조작하는 매커니즘이다. 리플렉션을 사용하면 동적으로 인스턴스를 생성하거나 기존 객체에 형식을 바인딩할 수 있으며 기존 객체의 정보를 가져와 해당 객체의 멤버를 조작할 수 있다.
C#은 리플렉션을 사용하기 위한 여러 클래스를 .NET 프레임워크에 정의해 놓았다. 아래는 그 리스트이다.
- Type
- MemberInfo
- ConstructorInfo
- MethodInfo
- FieldInfo
- PropertyInfo
- TypeInfo
- EventInfo
- Module
- Assembly
- AssemblyName
- Pointer etc.
📖Type 클래스
Type은 모든 형식(class, interface, array, value etc)의 선언을 대신할 수 있는 추상 클래스이다. 사용자는 객체의 모든 정보를 Type에 할당해 사용할 수 있는데, 이것이 가능한 이유는 C#의 최상위 클래스인 Object에 객체의 정보를 반환하는 함수가 정의되어 있어서이다.즉, C#의 모든 객체는 Object를 상속받으므로 Object의 함수를 이용해 객체의 정보를 가져올 수 있다.
아래 코드를 보면 이해가 쉽다.
using System;
public class ReflectionExample
{
public static void Main()
{
int a = 10;
Type type = a.GetType();
Console.WriteLine(type);
}
}
실행 결과:
System.Int32
📕어트리뷰트(Attribute)
📖어트리뷰트란?
어트리뷰트는 클래스, 메서드, 구조체, 어셈블리 등 다양한 요소의 동작 정보를 런타임 중 프로그램에 전달하기 위해 쓰는 선언적 태그다. 어트리뷰트를 나타내는 기호는 대괄호이며, 사용자는 요소 위에 어트리뷰트 작성함으로써 컴파일러 명령어와 메서드, 클래스 등 다양한 정보를 프로그램에 추가할 수 있다.
💡주석과 비슷하지만 사람이 아닌 컴퓨터가 읽는 정보라는 점에서 다르다.
📌어트리뷰트 작성법
[어트리뷰트_이름(어트리뷰트_매개 변수)]
public void TestMethod()
{
// ...
}
📖기본 제공 어트리뷰트
.NET 프레임워크는 Attribute 기본 클래스에 세 가지 어트리뷰트 클래스를 미리 정의해두었다.
- AttributeUsage
- Conditional
- Obsolete
📌AttributeUsage
다른 어트리뷰트 클래스의 사용법을 명시하는 어트리뷰트이다. AttributeUsage는 어트리뷰트를 정의하는 아래의 프로퍼티를 포함한다.
- VaildOn: 어트리뷰트를 적용할 요소를 지정한다.
- AllowMultiple: 어트리뷰트를 한 요소에 중첩해서 사용할 수 있는지 결정한다.
- Inherited: 어트리뷰트를 적용한 클래스의 파생클래스에도 해당 어트리뷰트가 적용되는지를 결정한다.
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
📌Conditional
메서드 및 프로퍼티의 실행 여부를 컴파일러에게 전달하는 어트리뷰트이다. 이때 메서드 및 프로퍼티의 실행 여부는 지정한 조건부 컴파일 기호에 따라 결정된다.
#define CONDITION1
#define CONDITION2
using System;
using System.Diagnostics;
class Test
{
static void Main()
{
Console.WriteLine("Calling Method1");
Method1(3);
Console.WriteLine("Calling Method2");
Method2();
Console.WriteLine("Using the Debug class");
Debug.Listeners.Add(new ConsoleTraceListener());
Debug.WriteLine("DEBUG is defined");
}
[Conditional("CONDITION1")]
public static void Method1(int x)
{
Console.WriteLine("CONDITION1 is defined");
}
[Conditional("CONDITION1"), Conditional("CONDITION2")]
public static void Method2()
{
Console.WriteLine("CONDITION1 or CONDITION2 is defined");
}
}
/*
When compiled as shown, the application (named ConsoleApp)
produces the following output.
Calling Method1
CONDITION1 is defined
Calling Method2
CONDITION1 or CONDITION2 is defined
Using the Debug class
DEBUG is defined
*/
📌Obsolete
더는 사용하지 않는 요소를 표시하는 어트리뷰트이다. 문자열 매개 변수를 전달해 해당 요소와 관련된 정보를 전달할 수 있다.
[Obsolete("ThisClass is obsolete. Use ThisClass2 instead.")]
public class ThisClass
{
}
📖사용자 정의 어트리뷰트
사용자가 직접 어트리뷰트를 정의해 사용하는 것도 가능하다. System.Attribute를 상속받는 클래스를 만들기만 하면 된다.
class Test : System.Attribute
{
// ...
}
System.Attribute를 상속받은 것만으로 Test라는 어트리뷰트가 생성되었다. 이렇게 생성한 어트리뷰트는 기본 제공 어트리뷰트처럼 대괄호를 사용해 적용할 수 있다.
🔖인용
https://www.javatpoint.com/c-sharp-reflection
C# Reflection - javatpoint
C# Reflection for beginners and professionals with examples on overloading, method overriding, inheritance, aggregation, base, polymorphism, sealed, abstract, interface, namespaces, exception handling, file io, collections, multithreading, reflection etc.
www.javatpoint.com
https://www.tutorialspoint.com/csharp/csharp_attributes.htm
C# - Attributes
C# - Attributes An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to
www.tutorialspoint.com
https://docs.microsoft.com/ko-kr/dotnet/csharp/tutorials/attributes
자습서: 특성 사용 - C#
C#에서 특성이 작동하는 방식을 알아봅니다.
docs.microsoft.com
'C#' 카테고리의 다른 글
[C#] 매개변수 한정자(ref, out, in) (1) | 2022.09.01 |
---|---|
[C#] 딕셔너리(Dictionary) (0) | 2022.07.08 |
제네릭(Generics)이란? (0) | 2022.06.24 |
구조체(Struct)와 클래스(Class) (0) | 2022.06.17 |
생성자 (0) | 2022.06.17 |