Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. [AttributeUsage(AttributeTargets.Method)]
  2. public class WorkAttribute : System.Attribute
  3. {
  4. public string Message;
  5.  
  6. public WorkAttribute(string message)
  7. {
  8. this.Message = message;
  9. }
  10. }
  11.  
  12. [Work("WorkMessage")]
  13. public void test(){...}
  14.  
  15. foreach (MethodInfo methodInfo in type.GetMethods())// type is the class's type
  16. {
  17. WorkAttribute workAttribute = methodInfo.GetCustomAttribute<WorkAttribute>();
  18. if (workAttribute != null)
  19. {
  20. Console.WriteLine(workAttribute.Message);// Should print "WorkMessage", but Message is null.
  21. }
  22. }
  23.  
  24. using System;
  25. using System.Collections.Generic;
  26. using System.Linq;
  27. using System.Reflection;
  28. using System.Text;
  29. using System.Threading.Tasks;
  30.  
  31. namespace ConsoleApplication1
  32. {
  33. [AttributeUsage(AttributeTargets.Method)]
  34. public class WorkAttribute : System.Attribute
  35. {
  36. public string Message;
  37.  
  38. public WorkAttribute(string message)
  39. {
  40. this.Message = message;
  41. }
  42. }
  43.  
  44. class Program
  45. {
  46. [Work("WorkMessage")]
  47. public void test()
  48. {
  49. }
  50.  
  51. static void Main()
  52. {
  53. foreach (MethodInfo methodInfo in typeof(Program).GetMethods())
  54. {
  55. WorkAttribute workAttribute = methodInfo.GetCustomAttribute<WorkAttribute>();
  56. if (workAttribute != null)
  57. {
  58. Console.WriteLine(workAttribute.Message);// Should print "WorkMessage", but Message is null.
  59. }
  60.  
  61. Console.ReadLine();
  62. }
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement