You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.4 KiB

  1. ---
  2. uti: com.xamarin.workbook
  3. id: de255e90-ba7b-4070-be45-65e544ae8219
  4. title: DecompilerPackageDemos
  5. platforms:
  6. - DotNetCore
  7. packages:
  8. - id: ICSharpCode.Decompiler
  9. version: 7.0.0.6488
  10. ---
  11. Setup: load the references required to work with the decompiler
  12. ```csharp
  13. #r "ICSharpCode.Decompiler"
  14. #r "System.Reflection.Metadata"
  15. using System.Reflection.Metadata;
  16. using ICSharpCode.Decompiler;
  17. using ICSharpCode.Decompiler.CSharp;
  18. using ICSharpCode.Decompiler.Metadata;
  19. using ICSharpCode.Decompiler.TypeSystem;
  20. // Version sanity check
  21. Console.WriteLine(typeof(FullTypeName).Assembly.GetName());
  22. ```
  23. You must have compiled **frontends.sln** first (run “dotnet build” in ICSharpCode.Decompiler.PowerShell folder)
  24. ```csharp
  25. string workbookBasePath = System.IO.Directory.GetCurrentDirectory();
  26. string fileName = System.IO.Path.Combine(workbookBasePath, "ICSharpCode.Decompiler.PowerShell", "bin", "Release", "netstandard2.0", "ICSharpCode.Decompiler.dll");
  27. var decompiler = new CSharpDecompiler(fileName, new DecompilerSettings());
  28. ```
  29. Get the count of types in this module
  30. ```csharp
  31. var types = decompiler.TypeSystem.MainModule.TypeDefinitions;
  32. Console.WriteLine(types.Count());
  33. ```
  34. Decompile a known type (as a whole)
  35. ```csharp
  36. // ICSharpCode.Decompiler.Util.Empty<T> -> translates to `n, where n is the # of generic parameters
  37. var nameOfGenericType = new FullTypeName("ICSharpCode.Decompiler.Util.Empty`1");
  38. Console.WriteLine(decompiler.DecompileTypeAsString(nameOfGenericType));
  39. ```
  40. If you want to decompile one single member (sample: first method)
  41. ```csharp
  42. var nameOfUniResolver = new FullTypeName("ICSharpCode.Decompiler.Metadata.UniversalAssemblyResolver");
  43. ITypeDefinition typeInfo = decompiler.TypeSystem.FindType(nameOfUniResolver).GetDefinition();
  44. var tokenOfFirstMethod = typeInfo.Methods.First().MetadataToken;
  45. Console.WriteLine(decompiler.DecompileAsString(tokenOfFirstMethod));
  46. ```
  47. If you need access to low-level metadata tables
  48. ```csharp
  49. ITypeDefinition type = decompiler.TypeSystem.FindType(nameOfUniResolver).GetDefinition();
  50. var module = type.ParentModule.PEFile;
  51. ```
  52. Get the child namespaces
  53. ```csharp
  54. var icsdns = decompiler.TypeSystem.RootNamespace;
  55. foreach (var ns in icsdns.ChildNamespaces) Console.WriteLine(ns.FullName);
  56. ```
  57. Get types in a single namespace
  58. ```csharp
  59. // ICSharpCode.Decompiler.TypeSystem is the first namespace
  60. var typesInNamespace = icsdns.ChildNamespaces.First().Types;
  61. ```