Generating System.Reflection objects
At compile time, the code mode is represented by objects of the Metalama.Framework.Code
namespace. However, at run time, the code model is represented by the System.Reflection
namespace. Although Metalama is designed in such a way that you do need any reflection in run-time code, there are still situation where you will want to get a System.Reflection
object in your run-time code.
To help in this situation, the Metalama.Framework.Code
exposes a few methods that generate expressions that return the System.Reflection
object that represents 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 examples introduce a method that returns a list of all methods, represented as a MethodInfo object, in the target type.
using Metalama.Framework.Aspects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Doc.EnumerateMethodInfos
{
internal class EnumerateMethodAspect : TypeAspect
{
[Introduce]
public IReadOnlyList<MethodInfo> GetMethods()
{
var methods = new List<MethodInfo>();
foreach ( var method in meta.Target.Type.Methods )
{
methods.Add( method.ToMethodInfo() );
}
return methods;
}
}
}
namespace Doc.EnumerateMethodInfos
{
[EnumerateMethodAspect]
internal class Foo
{
private void Method1() { }
private void Method2( int x, string y) { }
}
}
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Doc.EnumerateMethodInfos
{
[EnumerateMethodAspect]
internal class Foo
{
private void Method1() { }
private void Method2(int x, string y) { }
public IReadOnlyList<MethodInfo> GetMethods()
{
var methods = new List<MethodInfo>();
methods.Add(typeof(Foo).GetMethod("Method1", BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null)!);
methods.Add(typeof(Foo).GetMethod("Method2", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(int), typeof(string) }, null)!);
return methods;
}
}
}