PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/Rusty/Core/Helpers/Reflection.cs

http://github.com/polyethene/IronAHK
C# | 75 lines | 58 code | 16 blank | 1 comment | 12 complexity | f83cb25ab632b7373bccf2dbde27e839 MD5 | raw file
  1. using System;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. namespace IronAHK.Rusty
  5. {
  6. partial class Core
  7. {
  8. static object SafeInvoke(string name, params object[] args)
  9. {
  10. var method = FindLocalRoutine(name);
  11. if (method == null)
  12. return null;
  13. try
  14. {
  15. return method.Invoke(null, new object[] { args });
  16. }
  17. catch { }
  18. return null;
  19. }
  20. static void SafeSetProperty(object item, string name, object value)
  21. {
  22. var prop = item.GetType().GetProperty(name, value.GetType());
  23. if (prop == null)
  24. return;
  25. prop.SetValue(item, value, null);
  26. }
  27. static MethodInfo FindLocalRoutine(string name)
  28. {
  29. return FindLocalMethod(LabelMethodName(name));
  30. }
  31. static MethodInfo FindLocalMethod(string name)
  32. {
  33. var stack = new StackTrace(false).GetFrames();
  34. for (int i = 0; i < stack.Length; i++)
  35. {
  36. var type = stack[i].GetMethod().DeclaringType;
  37. if (type == typeof(Core))
  38. continue;
  39. // UNDONE: better way to check correct type for reflecting local methods
  40. if (type.FullName != "Program")
  41. continue;
  42. var list = type.GetMethods();
  43. for (int z = 0; z < list.Length; z++)
  44. if (list[z].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
  45. return list[z];
  46. }
  47. return null;
  48. }
  49. static string LabelMethodName(string raw)
  50. {
  51. foreach (var sym in raw)
  52. {
  53. if (!char.IsLetterOrDigit(sym))
  54. return string.Concat("label_", raw.GetHashCode().ToString("X"));
  55. }
  56. return raw;
  57. }
  58. }
  59. }