Metalama//Conceptual documentation/Creating aspects/Writing T# templates/Generating System.​Reflection objects
Open sandboxFocus

Generating System.Reflection objects

At compile time, the code model is represented by objects of the Metalama.Framework.Code namespace. At run time, the code model is represented by the System.Reflection namespace. Metalama is designed in such a way that you do not need any reflection in run-time code, but there are still situations where you will want a run-time System.Reflection object.

To help in this situation, the Metalama.Framework.Code namespace exposes a few methods that return the System.Reflection objects that represent 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()

Example

The following example introduces 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{
7    internal 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        }
22    }
23}
24
Source Code




1namespace Doc.EnumerateMethodInfos
2{
3    [EnumerateMethodAspect]
4    internal class Foo
5    {
6        private void Method1() { }
7        private void Method2( int x, string y) { }








8    }
9}
10
Transformed Code
1using System;
2using System.Collections.Generic;
3using System.Reflection;
4
5namespace Doc.EnumerateMethodInfos
6{
7    [EnumerateMethodAspect]
8    internal class Foo
9    {
10        private void Method1() { }
11        private void Method2(int x, string y) { }
12
13        public IReadOnlyList<MethodInfo> GetMethods()
14        {
15            var methods = new List<MethodInfo>();
16            methods.Add(typeof(Foo).GetMethod("Method1", BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null)!);
17            methods.Add(typeof(Foo).GetMethod("Method2", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(int), typeof(string) }, null)!);
18            return methods;
19        }
20    }
21}
22