简体   繁体   中英

Practical usage of params indexer

Recently, I have found out that indexer can accept an array of arguments as params :

public class SuperDictionary<TKey, TValue>
{
    public Dictionary<TKey, TValue> Dict { get; } = new Dictionary<TKey, TValue>();

    public IEnumerable<TValue> this[params TKey[] keys]
    {
        get { return keys.Select(key => Dict[key]); }
    }
}

Then, you will be able to do:

var sd = new SuperDictionary<string, object>();
/* Add values */
var res = sd["a", "b"];

However, I never met such usage in .NET Framework or any third-party libraries. Why has it been implemented? What is the practical usage of being able to introduce params indexer?

The answer has been found in a minute after posting the question and looking through the code and documentation - C# allows you to use any type as a parameter for indexer, but not params as a special case.

According to MSDN ,

Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

In other words, indexer can be of any type. It can either be an array...

public IEnumerable<TValue> this[TKey[] keys]
{
    get { return keys.Select(key => Dict[key]); }
}

var res = sd[new [] {"a", "b"}];

or any kind of another unusual type or collection, including params array, if it seems to be convenient and suitable in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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