code_junkie

Suggestions wanted with Lists or Enumerators of T when inheriting from generic classes

Nov 10th, 2011
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. public interface IOtherObjects;
  2.  
  3. public abstract class MyObjects<T> where T : IOtherObjects
  4. {
  5. ...
  6.  
  7. public List<T> ToList()
  8. {
  9. ...
  10. }
  11. }
  12.  
  13. public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
  14. {
  15.  
  16.  
  17. }
  18.  
  19. public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
  20. {
  21.  
  22.  
  23. }
  24.  
  25. class B : A
  26. class C : A
  27.  
  28. List<B> listB;
  29. List<C> listC;
  30.  
  31. List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()
  32.  
  33. foreach(var myObject in myObjectsList)
  34. foreach(var obj in myObject.ToList())
  35. //do something
  36.  
  37. // Original Code Snipped for Brevity - See Edit History if Req'd
  38.  
  39. public List<OfType> TypedList<OfType>() where OfType : IOtherObjects
  40. {
  41. List<OfType> rtn = new List<OfType>();
  42.  
  43. foreach (IOtherObjects o in _objects)
  44. {
  45. Type objType = o.GetType();
  46. Type reqType = typeof(OfType);
  47.  
  48. if (objType == reqType)
  49. rtn.Add((OfType)o);
  50. }
  51.  
  52. return rtn;
  53. }
  54.  
  55. public abstract class MyObjects<T> where T : IOtherObjects
  56. {
  57. List<T> _objects = new List<T>();
  58.  
  59. public List<T> ToList()
  60. {
  61. return _objects;
  62. }
  63.  
  64. public List<IOtherObjects> ToBaseList()
  65. {
  66. List<IOtherObjects> rtn = new List<IOtherObjects>();
  67. foreach (IOtherObjects o in _objects)
  68. {
  69. rtn.Add(o);
  70. }
  71. return rtn;
  72. }
  73. }
  74.  
  75. public abstract class MyObjects<T> where T : IOtherObjects
  76. {
  77. List<T> _objects = new List<T>();
  78.  
  79. public List<IOtherObjects> Objects
  80. { get { return _objects; } }
  81. }
  82. #warning This won't compile, its for demo's sake.
  83.  
  84. List<A>.Cast<B>().ToList<B>()
  85.  
  86. interface IMyObjects : IEnumerable<IOtherObjects> {}
  87. abstract class MyObjects<T> : IMyObjects where T : IOtherObjects {}
  88.  
  89. IEnumerable<IMyObjects> objs = ...;
  90. foreach (IMyObjects mo in objs) {
  91. foreach (IOtherObjects oo in mo) {
  92. Console.WriteLine(oo);
  93. }
  94. }
Add Comment
Please, Sign In to add comment