C# Multiple Indexers

后端 未结 7 1031
深忆病人
深忆病人 2020-12-30 05:10

Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        .         


        
相关标签:
7条回答
  • 2020-12-30 05:57

    There IS a way.. if you define 2 new types to alow the compiler to distinguish the two different signatures...

      public struct EmployeeId
      { 
          public int val;
          public EmployeeId(int employeeId) { val = employeeId; }
      }
      public struct HRId
      { 
          public int val;
          public HRId(int hrId) { val = hrId; }
      }
      public class Employee 
      {
          public int EmployeeId;
          public int HrId;
          // other stuff
      }
      public class Employees: Collection<Employee>
      {
          public Employee this[EmployeeId employeeId]
          {
              get
                 {
                    foreach (Employee emp in this)
                       if (emp.EmployeeId == employeeId.val)
                          return emp;
                    return null;
                 }
          }
          public Employee this[HRId hrId]
          {
              get
                 {
                    foreach (Employee emp in this)
                       if (emp.HRId == hrId.val)
                          return emp;
                    return null;
                 }
          }
          // (or using new C#6+ "expression-body" syntax)
          public Employee this[EmployeeId empId] => 
                 this.FirstorDefault(e=>e.EmployeeId == empId .val;
          public Employee this[HRId hrId] => 
                 this.FirstorDefault(e=>e.EmployeeId == hrId.val;
    
      }
    

    Then to call it you would have to write:

    Employee Bob = MyEmployeeCollection[new EmployeeID(34)];
    

    And if you wrote an implicit conversion operator:

    public static implicit operator EmployeeID(int x)
    { return new EmployeeID(x); }
    

    then you wouldn't even have to do that to use it, you could just write:

    Employee Bob = MyEmployeeCollection[34];
    

    Same thing applies even if the two indexers return different types...

    0 讨论(0)
提交回复
热议问题