Guest User

generic type dictionary

a guest
Feb 6th, 2014
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. public class PropMediator
  2. {
  3. public Dictionary<Type,IList> Hardware { get; set; }
  4. public PropMediator()
  5. {
  6. this.Hardware = new Dictionary<Type,IList>();
  7. }
  8. public void Add<T>(HardwareProp<T> hardware)
  9. {
  10. MethodInfo mi = this.GetType().GetMethod("AddIn", BindingFlags.NonPublic | BindingFlags.Instance);
  11. MethodInfo miConstructed = mi.MakeGenericMethod(hardware.GetType().GetGenericArguments()[0]);
  12. miConstructed.Invoke(this, new object[] { hardware.val });
  13. }
  14. private void AddIn<T>(T val)
  15. {
  16. if(!this.Hardware.ContainsKey(typeof(T)))
  17. {
  18. this.Hardware[typeof(T)] = new List<T>();
  19. }
  20. this.Hardware[typeof(T)].Add(val);
  21. }
  22. }
  23.  
  24. public class HardwareProp<T>
  25. {
  26. public T val { get; set; }
  27. }
  28.  
  29. public class SomeClass
  30. {
  31. public int i { get; set; }
  32. public SomeClass(int i)
  33. {
  34. this.i = i;
  35. }
  36. }
  37.  
  38. void Main()
  39. {
  40. var mediator = new PropMediator();
  41.  
  42. foreach( int i in Enumerable.Range(0,4).ToList() )
  43. {
  44. var prop = new HardwareProp<int>();
  45. prop.val = i;
  46. mediator.Add(prop);
  47. }
  48.  
  49. foreach( int i in Enumerable.Range(0,4).ToList() )
  50. {
  51. var prop = new HardwareProp<string>();
  52. prop.val = "val" + i;
  53. mediator.Add(prop);
  54. }
  55.  
  56. foreach( int i in Enumerable.Range(0,4).ToList() )
  57. {
  58. var prop = new HardwareProp<SomeClass>();
  59. prop.val = new SomeClass(i);
  60. mediator.Add(prop);
  61. }
  62.  
  63. foreach( var item in mediator.Hardware )
  64. {
  65. Console.WriteLine(item.Key);
  66. foreach(var val in (IList)item.Value)
  67. {
  68. Console.WriteLine(val);
  69. }
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment