是否有可能具有以下内容:
class C { public Foo Foos[int i] { ... } public Bar Bars[int i] { ... } }
如果没有,那么我可以通过哪些方式实现这一目标?我知道我可以创建名为getFoo(int i)和getBar(int i)的函数,但我希望用属性来做这个.
不是在C#中,没有.
但是,您始终可以从属性返回集合,如下所示:
public IListFoos { get { return ...; } } public IList Bars { get { return ...; } }
IList
C whatever = new C(); Foo myFoo = whatever.Foos[13];
在线上"返回...;" 你可以返回任何实现IList
这来自C#3.0规范
"重载索引器允许类,结构或接口声明多个索引器,前提是它们的签名在该类,结构或接口中是唯一的."
public class MultiIndexer : List{ public string this[int i] { get{ return this[i]; } } public string this[string pValue] { get { //Just to demonstrate return this.Find(x => x == pValue); } } }
有一种方法..如果您定义2个新类型以使编译器能够区分两个不同的签名...
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{ 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; }
然后调用它,您将必须编写:
Employee Bob = MyEmployeeCollection[new EmployeeID(34)];
如果您编写了一个隐式转换运算符:
public static implicit operator EmployeeID(int x) { return new EmployeeID(x); }
那么您甚至不必这样做就可以使用它,您可以编写:
Employee Bob = MyEmployeeCollection[34];
即使两个索引器返回不同的类型,情况也一样。