The*_*iot 5 c# properties indexed-properties
假设我在类中有一个数组或任何其他集合,以及一个返回它的属性,如下所示:
public class Foo
{
public IList<Bar> Bars{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
现在,我可以这样写:
public Bar Bar[int index]
{
get
{
//usual null and length check on Bars omitted for calarity
return Bars[index];
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 11
不 - 你不能在C#中编写命名索引器.从C#4开始,您可以将它们用于COM对象,但是您无法编写它们.
然而,正如你所注意到的那样,无论如何foo.Bars[index]都会做你想要的......这个答案主要是为了未来的读者.
详细说明:公开Bars具有索引器的某种类型的属性可以实现您想要的,但您应该考虑如何公开它:
根据您真正需要的内容,它可能已经为您完成。如果您尝试在 Bars 集合上使用索引器,它已经为您完成了::
Foo myFoo = new Foo();
Bar myBar = myFoo.Bars[1];
Run Code Online (Sandbox Code Playgroud)
或者,如果您想获得以下功能:
Foo myFoo = new Foo();
Bar myBar = myFoo[1];
Run Code Online (Sandbox Code Playgroud)
然后:
public Bar this[int index]
{
get { return Bars[index]; }
}
Run Code Online (Sandbox Code Playgroud)