The code model is represented by objects from the Metalama.Framework.Code
namespace at compile time and by objects from the System.Reflection
namespace at run time. Metalama is designed to eliminate the need for reflection in run-time code. However, there may be situations where you might require a run-time System.Reflection
object.
To accommodate these situations, the Metalama.Framework.Code
namespace provides several methods that return System.Reflection
objects, representing the desired declaration at run time.
Compile-time type | Run-time type | Conversion method |
---|---|---|
IType | Type | ToType() |
IMemberOrNamedType | MemberInfo | ToMemberInfo() |
IField | FieldInfo | ToFieldInfo() |
IPropertyOrIndexer | PropertyInfo | ToPropertyInfo() |
IMethodBase | MethodBase | ToMethodBase() |
IMethod | MethodInfo | ToMethodInfo() |
IConstructor | ConstructorInfo | ToConstructorInfo() |
IParameter | ParameterInfo | ToParameterInfo() |
Warning
The code generated by these methods may break if your project is obfuscated.
Example
The following example demonstrates a method that returns a list of all methods represented as MethodInfo objects in the target type.
1using Metalama.Framework.Aspects;
2using System.Collections.Generic;
3using System.Reflection;
4
5namespace Doc.EnumerateMethodInfos;
6
7internal class EnumerateMethodAspect : TypeAspect
8{
9 [Introduce]
10 public IReadOnlyList<MethodInfo> GetMethods()
11 {
12 var methods = new List<MethodInfo>();
13
14 foreach ( var method in meta.Target.Type.Methods )
15 {
16 methods.Add( method.ToMethodInfo() );
17 }
18
19 return methods;
20 }
21}
Source Code
1namespace Doc.EnumerateMethodInfos;
2
3[EnumerateMethodAspect]
4internal class Foo
5{
6 private void Method1() { }
7
8 private void Method2( int x, string y ) { }
9}
Transformed Code
1using System;
2using System.Collections.Generic;
3using System.Reflection;
4
5namespace Doc.EnumerateMethodInfos;
6
7[EnumerateMethodAspect]
8internal class Foo
9{
10 private void Method1() { }
11
12 private void Method2(int x, string y) { }
13
14 public IReadOnlyList<MethodInfo> GetMethods()
15 {
16 var methods = new List<MethodInfo>();
17 methods.Add(typeof(Foo).GetMethod("Method1", BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null));
18 methods.Add(typeof(Foo).GetMethod("Method2", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(int), typeof(string) }, null));
19 return methods;
20 }
21}