简体   繁体   English

为具有多个数组的类创建索引器?

[英]creating indexer for a class with more than one array?

So I'm reading about indexers and basically understands that if you have a class with an array in it, you can use an indexer to get and set values inside that array. 因此,我正在阅读有关索引器的信息,并且基本上理解,如果您有一个带有数组的类,则可以使用索引器来获取和设置该数组中的值。 But what if you have more than one array in your class? 但是,如果您的班级中有多个数组怎么办?

for example: 例如:

class myClass
{
     string[] myArray1 = {"joe","zac","lisa"}
     string[] myArray2 = {"street1","street2","street3"}
}

and I want to have an indexer for both myArray1 and myArray2... how can i do that? 我想同时为myArray1和myArray2建立索引器...我该怎么做?

You can't, basically. 基本上你不能。 Well, you could overload the index, making one take long indexes and one take int indexes for example, but that's very unlikely to be a good idea, and may cause serious irritation to those who come after you maintaining the code. 好吧,您可能会使索引超载,例如使一个采用long索引,而使一个采用int索引,但这并不是一个好主意,并且可能会给维护代码后的人们带来极大的困扰。

What's more likely to be useful is to expose normal properties instead, which wrap the array (and possibly only provide read-only access). 更可能有用的是改为公开常规属性,该常规属性包装了数组(并且可能仅提供只读访问权限)。 You can use ReadOnlyCollection<T> for this in some cases: 在某些情况下,可以使用ReadOnlyCollection<T>

public class Foo
{
    private readonly string[] names;
    private readonly string[] addresses;

    // Assuming you're using C# 6...
    private readonly ReadOnlyCollection<string> Names { get; }
    private readonly ReadOnlyCollection<string> Addresses { get; }

    public Foo()
    {
        names = ...;
        addresses = ...;
        Names = new ReadOnlyCollection<string>(names);
        Addresses = new ReadOnlyCollection<string>(addresses);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM