Extensions.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text.RegularExpressions;
  6. namespace Harmony
  7. {
  8. public static class GeneralExtensions
  9. {
  10. public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ")
  11. {
  12. if (converter == null) converter = t => t.ToString();
  13. return enumeration.Aggregate("", (prev, curr) => prev + (prev != "" ? delimiter : "") + converter(curr));
  14. }
  15. public static string Description(this Type[] parameters)
  16. {
  17. if (parameters == null) return "NULL";
  18. var pattern = @", \w+, Version=[0-9.]+, Culture=neutral, PublicKeyToken=[0-9a-f]+";
  19. return "(" + parameters.Join(p => p?.FullName == null ? "null" : Regex.Replace(p.FullName, pattern, "")) + ")";
  20. }
  21. public static string FullDescription(this MethodBase method)
  22. {
  23. var parameters = method.GetParameters().Select(p => p.ParameterType).ToArray();
  24. return method.DeclaringType.FullName + "." + method.Name + parameters.Description();
  25. }
  26. public static Type[] Types(this ParameterInfo[] pinfo)
  27. {
  28. return pinfo.Select(pi => pi.ParameterType).ToArray();
  29. }
  30. public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key)
  31. {
  32. T result;
  33. if (dictionary.TryGetValue(key, out result))
  34. return result;
  35. return default(T);
  36. }
  37. public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key)
  38. {
  39. object result;
  40. if (dictionary.TryGetValue(key, out result))
  41. if (result is T)
  42. return (T)result;
  43. return default(T);
  44. }
  45. }
  46. public static class CollectionExtensions
  47. {
  48. public static void Do<T>(this IEnumerable<T> sequence, Action<T> action)
  49. {
  50. if (sequence == null) return;
  51. var enumerator = sequence.GetEnumerator();
  52. while (enumerator.MoveNext()) action(enumerator.Current);
  53. }
  54. public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action)
  55. {
  56. sequence.Where(condition).Do(action);
  57. }
  58. public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)
  59. {
  60. return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });
  61. }
  62. public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
  63. {
  64. return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
  65. }
  66. public static T[] AddToArray<T>(this T[] sequence, T item)
  67. {
  68. return Add(sequence, item).ToArray();
  69. }
  70. }
  71. }