命名索引器属性可能吗? [英] Is named indexer property possible?

查看:53
本文介绍了命名索引器属性可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在类中有一个与此相关的数组或任何其他集合,并且有一个属性将其返回,如下所示:

Suppose I have an array or any other collection for that matter in class and a property which returns it like following:

public class Foo
{
    public IList<Bar> Bars{get;set;}
}

现在,我可以这样写吗:

Now, may I write anything like this:

public Bar Bar[int index]
{
    get
    {
        //usual null and length check on Bars omitted for calarity
        return Bars[index];
    }
}

推荐答案

根据您的实际需求,可能已经为您完成了.如果您尝试在Bars集合上使用索引器,则已经为您完成了::

Depending on what you're really looking for, it might already be done for you. If you're trying to use an indexer on the Bars collection, it's already done for you::

Foo myFoo = new Foo();
Bar myBar = myFoo.Bars[1];

或者,如果您尝试获得以下功能:

Or if you're trying to get the following functionality:

Foo myFoo = new Foo();
Bar myBar = myFoo[1];

然后:

public Bar this[int index]
{
    get { return Bars[index]; }
}

这篇关于命名索引器属性可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆