리플렉션 개체는 런타임에 형식 정보를 얻는 데 사용됩니다. 실행 중인 프로그램의 메타데이터에 대한 액세스를 제공하는 클래스는 System.Reflection 네임스페이스에 있습니다.
다음은 반사의 응용 프로그램입니다 -
- 런타임에 속성 정보를 볼 수 있습니다.
- 어셈블리에서 다양한 유형을 검사하고 이러한 유형을 인스턴스화할 수 있습니다.
- 메소드 및 속성에 대한 후기 바인딩 허용
- 런타임에 새로운 유형을 생성한 다음 해당 유형을 사용하여 일부 작업을 수행할 수 있습니다.
System.Reflection 네임스페이스에는 응용 프로그램에 대한 정보를 얻고 응용 프로그램에 유형, 값 및 개체를 동적으로 추가할 수 있는 클래스가 포함되어 있습니다.
예도 살펴보겠습니다.
아래에서 대상 클래스의 개체를 설정했습니다 -
System.Reflection.MemberInfo info = typeof(MyClass);
다음은 완전한 예입니다 -
예시
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute {
public readonly string Url;
public string Topic {
get {
return topic;
}
set {
topic = value;
}
}
public HelpAttribute(string url) { // url is a positional parameter
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass {
}
namespace AttributeAppl {
class Program {
static void Main(string[] args) {
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++) {
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
} 출력
HelpAttribute