Array that can be accessed using array['Name'] in C#

前端 未结 3 1326
心在旅途
心在旅途 2021-02-08 00:38

Can you do

array[\'Name\'];

In C#

Rather than:

array[0];

I know you can do that in PHP but is there a

3条回答
  •  失恋的感觉
    2021-02-08 00:51

    Arrays don't work like that in C#, but you can add an indexer property to any class:

    class MyClass
    {
        public string this[string key]
        {
            get { return GetValue(key); }
            set { SetValue(key, value); }
        }
    }
    

    Then you can write the type of statements you ask against this:

    MyClass c = new MyClass();
    c["Name"] = "Bob";
    

    This is how string-based indexed access to Dictionary, NameValueCollection and similar classes are implemented. You can implement multiple indexers as well, for example, one for the index and one for the name, you just add another property as above with a different parameter type.

    Several built-in framework classes already have these indexers, including:

    • SortedList
    • Dictionary
    • SortedDictionary
    • NameValueCollection
    • Lookup (in System.Linq)

    ...and more. These are all designed for slightly different purposes, so you'll want to read up on each and see which one's appropriate for your requirement.

提交回复
热议问题