code_junkie

Retrieving annotated method from attribute constructor

Nov 12th, 2011
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. public class ErrorHandler
  2. {
  3. [HandleMessage(ErrorHandling.ERROR)]
  4. private static void OnError(string message, object context, params object[] args)
  5. {
  6. Exception e;
  7. args.Extract(out e);
  8.  
  9. Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
  10. }
  11. }
  12.  
  13. public static void RegisterStaticHandlers(Type type)
  14. {
  15. foreach (var mInfo in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static))
  16. {
  17. var mAttr = mInfo.GetCustomAttribute<HandleMessageAttribute>();
  18. if (mAttr != null)
  19. RegisterInstanceHandler(mAttr.Message, mInfo.CreateDelegate<MessageHandler>());
  20. }
  21. }
  22.  
  23. public class HandleMessageAttribute : Attribute
  24. {
  25. public string Message { get; private set; }
  26.  
  27. public HandleMessageAttribute(string message)
  28. {
  29. Message = message;
  30.  
  31. Messages.RegisterInstanceHandler(message, ... method reference here ...);
  32. }
  33. }
  34.  
  35. static ErrorHandler()
  36. {
  37. Messages.RegisterStaticHandlers(typeof(ErrorHandler));
  38. }
Add Comment
Please, Sign In to add comment