Type, MethodInfo, 활성화와 사용자 지정 특성
Type 객체를 가져오고, MethodInfo를 찾고, 메서드를 호출하며, Activator로 인스턴스를 만들고, 사용자 지정 특성을 정의하고 읽습니다.
Type, MethodInfo, 활성화와 사용자 지정 특성은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 3개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.
개요
목표: 리플렉션을 안전하게 사용합니다.
- Type 가져오기
- MethodInfo 찾기
- Activator를 사용하여 생성하기
- 특성 정의 및 읽기
Type 가져오기
typeof, GetType()을 사용하는 인스턴스 또는 이름을 통한 Type.GetType으로 Type을 가져옵니다.
using System;
public class Sample { }
public class Program
{
public static void Main(string[] args)
{
// 1) From a compile-time type
Type t1 = typeof(Sample);
// 2) From an instance
Sample s = new Sample();
Type t2 = s.GetType();
// 3) From a full name (needs assembly-qualified name for external types)
Type t3 = Type.GetType("System.String");
Console.WriteLine(t1.Name + ", " + t2.FullName + ", " + (t3 == null ? "null" : t3.Name));
}
}
MethodInfo.Invoke
GetMethod로 메서드를 찾고 Invoke로 호출합니다. 인스턴스와 인수 배열을 전달합니다.
using System;
using System.Reflection;
public class Greeter
{
public string Hello(string name) { return "Hello, " + name; }
}
public class Program
{
public static void Main(string[] args)
{
Greeter g = new Greeter();
Type t = typeof(Greeter);
MethodInfo mi = t.GetMethod("Hello"); // public instance method
object result = mi.Invoke(g, new object[] { "Ada" }); // call dynamically
Console.WriteLine(result); // Hello, Ada
}
}
Activator 기본
Activator.CreateInstance(Type)은 공개 매개 변수가 없는 생성자를 사용하여 개체를 생성합니다.
using System;
public class Person
{
public string Name { get; set; }
public Person() { Name = "Unknown"; } // parameterless ctor
}
public class Program
{
public static void Main(string[] args)
{
Type tp = typeof(Person);
object o = Activator.CreateInstance(tp); // uses public parameterless ctor
Person p = (Person)o;
p.Name = "Alan";
Console.WriteLine("Created: " + p.Name);
}
}
사용자 지정 특성
작은 Attribute 클래스를 만들고, 형식이나 메서드에서 GetCustomAttributes를 통해 가져옵니다.
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class LabelAttribute : Attribute
{
public string Text { get; private set; }
public LabelAttribute(string text) { Text = text; }
}
[Label("Utility class")]
public class Utils
{
[Label("Adds two ints")]
public static int Add(int a, int b) { return a + b; }
}
public class Program
{
public static void Main(string[] args)
{
Type t = typeof(Utils);
// Read class attribute
object[] classAttrs = t.GetCustomAttributes(typeof(LabelAttribute), false);
if (classAttrs.Length > 0)
Console.WriteLine("Class label: " + ((LabelAttribute)classAttrs[0]).Text);
// Read method attribute
MethodInfo mi = t.GetMethod("Add");
object[] methodAttrs = mi.GetCustomAttributes(typeof(LabelAttribute), false);
if (methodAttrs.Length > 0)
Console.WriteLine("Method label: " + ((LabelAttribute)methodAttrs[0]).Text);
}
}
팁 및 안전 수칙
팁:
- Type.GetType에서 null이 반환되는 경우와 멤버가 누락된 경우를 확인하십시오.
- 가능하면 typeof를 우선 사용하십시오(더 빠르고 안전합니다).
- 리플렉션 사용을 한곳에 모으고 문서화하십시오.
- 공개되지 않은 멤버나 정적 멤버를 검색할 때는 BindingFlags를 사용하십시오.
활성화 기본
복습
복습: Type을 가져오고, MethodInfo를 찾고, Activator로 생성한 다음, GetCustomAttributes를 사용하여 특성을 읽습니다.
자주 묻는 질문
“Type, MethodInfo, 활성화와 사용자 지정 특성” 강의는 무료인가요?
네 — “Type, MethodInfo, 활성화와 사용자 지정 특성” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.
“Type, MethodInfo, 활성화와 사용자 지정 특성”에서 뭘 배우나요?
Type 객체를 가져오고, MethodInfo를 찾고, 메서드를 호출하며, Activator로 인스턴스를 만들고, 사용자 지정 특성을 정의하고 읽습니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C# Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 1번째 강의입니다.
“Type, MethodInfo, 활성화와 사용자 지정 특성” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Type, MethodInfo, 활성화와 사용자 지정 특성
- 소스 수준 정보(Caller 특성)
- 가벼운 메타프로그래밍 시나리오