Reflection
리νλ μ μ νμ©νλ©΄ λμ μΌλ‘ λ©μλλ μμ±νκ³ , λμ μΌλ‘ μΈμ€ν΄μ€λ₯Ό μμ±ν΄μ λ©μλλ₯Ό μ€νμν¬ μ μλ€.
1. Assembly λ§λ€κΈ°
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("CalculatorAssembly"), AssemblyBuilderAccess.Run);
2. Assembly μμ Module λ§λ€κΈ°
ModuleBuilder module = assembly.DefineDynamicModule("CalculatorModule");
3. Module μμ Class λ§λ€κΈ°
TypeBuilder type = module.DefineType("CalculatorClass");
4. Class μμ Method λ§λ€κΈ°
MethodBuilder method = type.DefineMethod(
"Add",
MethodAttributes.Public,
typeof(int), // return type
new Type[] { typeof(int), typeof(int) }); // parameter types
5. ILGeneratorλ₯Ό μ¬μ©ν΄μ Method μμ±μν€κΈ°
ILGenerator generator = method.GetILGenerator();
generator.Emit(OpCodes.Ldarg_1); // args[0]
generator.Emit(OpCodes.Ldarg_2); // args[1]
generator.Emit(OpCodes.Add); // added
generator.Emit(OpCodes.Ret); // return
μ μ½λλ λ μΈμλ₯Ό λ°μ Add νλ λ©μλμ΄λ€. μ¦, μλ λ©μλλ₯Ό λ§λλ μ½λμ΄λ€.
public int Add(int a, int b)
{
return a + b;
}
6. Type μμ±μν€κΈ°
Type dynamicType = type.CreateType();
7. λμ μΈμ€ν΄μ€ μμ± ν λ©μλ μ€νμν€κΈ°
object instance = Activator.CreateInstance(dynamicType);
MethodInfo calculate = dynamicType.GetMethod("Add");
Console.WriteLine(calculate.Invoke(instance, new object[] { 5, 7 }));
λμ λ©μλλ₯Ό μμ±νλ©΄ μ μ°μ±κ³Ό νμ₯μ±μ λ¬Όλ‘ μ΄κ³ , μ½λλ₯Ό λ€μ μ»΄νμΌνκ±°λ λ€μ λΉλν νμ μμ΄ μλ‘μ΄ κΈ°λ₯μ λμ νκ±°λ μ½λλ₯Ό μμ ν μ μλ€λ ν° μ₯μ μ΄ μλ€.
'π₯οΈ > C#' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[C#] μ€λ λμ ν¬λ¦¬ν°μ»¬ μΉμ (Critical Section) (0) | 2023.10.11 |
---|---|
[C#] μ€λ λ(Thread) (0) | 2023.10.11 |
[C#] 리νλ μ (Reflection): λμ μΈμ€ν΄μ€ μμ±νκΈ° (0) | 2023.10.10 |
[C#] 리νλ μ (Reflection) (0) | 2023.10.10 |
[μ΄κ²μ΄ C#μ΄λ€] Chapter15: μ°μ΅λ¬Έμ (LINQ) (0) | 2023.10.05 |