code_junkie

C# Multiple Indexers

Nov 13th, 2011
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. class C
  2. {
  3. public Foo Foos[int i]
  4. {
  5. ...
  6. }
  7.  
  8. public Bar Bars[int i]
  9. {
  10. ...
  11. }
  12. }
  13.  
  14. public IList<Foo> Foos
  15. {
  16. get { return ...; }
  17. }
  18.  
  19. public IList<Bar> Bars
  20. {
  21. get { return ...; }
  22. }
  23.  
  24. C whatever = new C();
  25. Foo myFoo = whatever.Foos[13];
  26.  
  27. var myClass = new MyClass();
  28.  
  29. Console.WriteLine(myClass.Foos[0]);
  30. Console.WriteLine(myClass.Bars[0]);
  31.  
  32. public class C {
  33. private string[] foos = new string[] { "foo1", "foo2", "foo3" };
  34. private string[] bars = new string[] { "bar1", "bar2", "bar3" };
  35. public string[] Foos { get { return foos; } }
  36. public string[] Bars { get { return bars; } }
  37. }
  38.  
  39. C myThing = new C();
  40. Console.WriteLine(myThing.Foos[1]);
  41. Console.WriteLine(myThing.Bars[2]);
  42.  
  43. public class MultiIndexer : List<string>
  44. {
  45. public string this[int i]
  46. {
  47. get{
  48. return this[i];
  49. }
  50. }
  51. public string this[string pValue]
  52. {
  53. get
  54. {
  55. //Just to demonstrate
  56. return this.Find(x => x == pValue);
  57. }
  58. }
  59. }
  60.  
  61. public struct EmployeeId
  62. {
  63. public int val;
  64. public EmployeeId(knt employeeId) { val = employeeId; }
  65. }
  66. public struct HRId
  67. {
  68. public int val;
  69. public HRId(knt hrId) { val = hrId; }
  70. }
  71. public class Employee
  72. {
  73. public int EmployeeId;
  74. public int HrId;
  75. // other stuff
  76. }
  77. public class Employees: Collection<Employee>
  78. {
  79. public Employee this[EmployeeId employeeId]
  80. {
  81. get
  82. {
  83. foreach (Employee emp in this)
  84. if (emp.EmployeeId == employeeId.val)
  85. return emp;
  86. return null;
  87. }
  88. }
  89. public Employee this[HRId hrId]
  90. {
  91. get
  92. {
  93. foreach (Employee emp in this)
  94. if (emp.HRId == hrId.val)
  95. return emp;
  96. return null;
  97. }
  98. }
  99. }
  100.  
  101. Employee Bob = MyEmployeeCollection[new EmployeeID(34)];
Add Comment
Please, Sign In to add comment