Skip to content

Instantly share code, notes, and snippets.

@gogsbread
Created January 2, 2013 23:11
Show Gist options
  • Save gogsbread/4439232 to your computer and use it in GitHub Desktop.
Save gogsbread/4439232 to your computer and use it in GitHub Desktop.
Comparing reflection using Mono.Cecil and .NET Reflection.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using System.IO;
class Reflect
{
static void Main()
{
//Assembly
//Module
//Types
//Members
RefelctionUsingCecil();
ReflectUsingRefelction();
}
static void RefelctionUsingCecil()
{
AssemblyDefinition a = AssemblyDefinition.ReadAssembly(new FileStream("ModuleAssembly.exe",FileMode.Open,FileAccess.Read));
IEnumerable<ModuleDefinition> ms = a.Modules;
foreach (ModuleDefinition m in ms)
{
IEnumerable<TypeDefinition> ts = m.Types;
ConsoleWriter(0, m.Name);
foreach (TypeDefinition t in ts)
{
ConsoleWriter(1, t.FullName);
if (t.FullName != "<Module>")
{
//Console.WriteLine(t.DeclaringType.Name); //Explore using debug mode in IDE
//IEnumerable<MethodDefinition> mes = t.Methods.Where(def => { return def.IsPublic || def.IsPrivate || def.IsVirtual; });
IEnumerable<MethodDefinition> mes = t.Methods;// same as def.isPublic || def.isPrivate // Guess the datastructure that holds the parent references is undocumented and hence Mono.cecil cannot navigate.
foreach (MethodDefinition me in mes)
{
ConsoleWriter(2, me.Name);
}
}
}
Console.WriteLine();
}
}
static void ReflectUsingRefelction()
{
Assembly a = Assembly.LoadFrom("ModuleAssembly.exe");
Module[] ms = a.GetModules();
foreach (Module m in ms)
{
ConsoleWriter(0, m.Name);
Type[] ts = m.GetTypes();
foreach (Type t in ts)
{
ConsoleWriter(1, t.FullName);
MemberInfo[] mes = t.GetMembers(BindingFlags.Public | BindingFlags.Instance);
foreach (MemberInfo me in mes)
{
ConsoleWriter(2, me.Name);
}
}
Console.WriteLine();
}
}
static void ConsoleWriter(int level, string data)
{
Console.WriteLine("{0}{1}", Enumerable.Repeat<string>("-", level).Flatten(), data);
}
}
internal static class IEnumerableExtensions
{
internal static string Flatten(this IEnumerable<string> collection)
{
string retValue = string.Empty;
foreach (string o in collection)
{
try
{
retValue += o;
}
catch
{
}
}
return retValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment