C#多个索引器 [英] C# Multiple Indexers

查看:169
本文介绍了C#多个索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能有类似以下内容:

Is it possible to have something like the following:

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

    public Bar Bars[int i]
    {
        ...
    }
}

如果不是,那么是有一些方法我能做到这一点?我知道我可以做函数调用的getFoo(int i)以和getBar(int i)以,但我希望能与性能做到这一点。

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

推荐答案

不是在C#,没有

不过,您可以随时返回从属性集合,如下所示:

However, you can always return collections from properties, as follows:

public IList<Foo> Foos
{
    get { return ...; }
}

public IList<Bar> Bars
{
    get { return ...; }
}



&IList的LT; T>有一个索引,所以你可以写以下内容:

IList<T> has an indexer, so you can write the following:

C whatever = new C();
Foo myFoo = whatever.Foos[13];

在行返回...;你可以返回任何实现IList< T> ;,但你可能什么返回围绕您的收藏只读的包装,看AsReadOnly()方法。

On the lines "return ...;" you can return whatever implements IList<T>, but you might what to return a read-only wrapper around your collection, see AsReadOnly() method.

这篇关于C#多个索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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