Extensions.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.CodeDom;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using Microsoft.CSharp;
  6. namespace Chronos.Reflection.Editor
  7. {
  8. public static class Extensions
  9. {
  10. // Used to print pretty type names for primitives
  11. private static CSharpCodeProvider csharp = new CSharpCodeProvider();
  12. /// <summary>
  13. /// Returns the name for the given type where primitives are in their shortcut form.
  14. /// </summary>
  15. public static string PrettyName(this Type type)
  16. {
  17. string cSharpOutput = csharp.GetTypeOutput(new CodeTypeReference(type));
  18. var matches = Regex.Matches(cSharpOutput, @"([a-zA-Z0-9_\.]+)");
  19. var prettyName = RemoveNamespace(matches[0].Value);
  20. if (matches.Count > 1)
  21. {
  22. prettyName += "<";
  23. prettyName += string.Join(", ", matches.Cast<Match>().Skip(1).Select(m => RemoveNamespace(m.Value)).ToArray());
  24. prettyName += ">";
  25. }
  26. return prettyName;
  27. }
  28. private static string RemoveNamespace(string typeFullName)
  29. {
  30. if (!typeFullName.Contains('.'))
  31. {
  32. return typeFullName;
  33. }
  34. return typeFullName.Substring(typeFullName.LastIndexOf('.') + 1);
  35. }
  36. }
  37. }