Permalink
3fb25e5 Aug 13, 2018
2 contributors

Users who have contributed to this file

@christophwille @siegfriedpammer
79 lines (61 sloc) 2.38 KB
uti id title platforms packages
com.xamarin.workbook
de255e90-ba7b-4070-be45-65e544ae8219
DecompilerPackageDemos
DotNetCore
id version
ICSharpCode.Decompiler
4.0.0.4319-beta2

Setup: load the references required to work with the decompiler

#r "ICSharpCode.Decompiler"
#r "System.Reflection.Metadata"

using System.Reflection.Metadata;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;

// Version sanity check
Console.WriteLine(typeof(FullTypeName).Assembly.GetName());

You must have compiled frontends.sln first (run “dotnet build” in ICSharpCode.Decompiler.PowerShell folder)

string workbookBasePath = System.IO.Directory.GetCurrentDirectory();
string fileName = System.IO.Path.Combine(workbookBasePath, "ICSharpCode.Decompiler.PowerShell", "bin", "Debug", "netstandard2.0", "ICSharpCode.Decompiler.dll");
var decompiler = new CSharpDecompiler(fileName, new DecompilerSettings());

Get the count of types in this module

var types = decompiler.TypeSystem.MainModule.TypeDefinitions;
Console.WriteLine(types.Count());

Decompile a known type (as a whole)

// ICSharpCode.Decompiler.Util.Empty<T> -> translates to `n, where n is the # of generic parameters
var nameOfGenericType = new FullTypeName("ICSharpCode.Decompiler.Util.Empty`1");
Console.WriteLine(decompiler.DecompileTypeAsString(nameOfGenericType));

If you want to decompile one single member (sample: first property)

var nameOfUniResolver =  new FullTypeName("ICSharpCode.Decompiler.UniversalAssemblyResolver");
ITypeDefinition typeInfo = decompiler.TypeSystem.FindType(nameOfUniResolver).GetDefinition();
var tokenOfFirstProperty = typeInfo.Properties.First().MetadataToken;
Console.WriteLine(decompiler.DecompileAsString(tokenOfFirstProperty));

If you need access to low-level metadata tables

ITypeDefinition type = decompiler.TypeSystem.FindType(nameOfUniResolver).GetDefinition();
var module = type.ParentModule.PEFile;

Get the child namespaces

var icsdns = decompiler.TypeSystem.RootNamespace;
foreach (var ns in icsdns.ChildNamespaces) Console.WriteLine(ns.FullName);

Get types in a single namespace

// ICSharpCode.Decompiler.TypeSystem is the first namespace
var typesInNamespace = icsdns.ChildNamespaces.First().Types;