Jak ze třídy udělat pole - C# indexery

Možná jeden z méně známých, nicméně užitečných konceptů v C# jsou tzv. indexery. Indexer (někdy také označován jako smart array) nám umožní zacházet s objektem třídy jako kdyby se jednalo o pole.

Class c = new Class();
c.Foo();
c[
0] = "abc";
c[
1] = "def";

Demo

Definována je jedna třída ClassArray používající indexer a dále metoda pro výpis prvků v poli, prvky jsou uloženy v _items.

ClassArray.cs

using System;
using System.Collections.Generic;

namespace CSharpIndexer
{
    class ClassArray
    {
        private Dictionary<string, string> _items = new Dictionary<string,string>();

        // indexer
        public string this[string index]
        {
            get
            {
                return _items[index];
            }
            set
            {
                _items[index] = value;
            }
        }

        // simple method
        public string Dump()
        {
            string str = string.Empty;

            foreach (string key in _items.Keys)
                str += string.Format("{0}: {1}{2}", key, _items[key], Environment.NewLine);

            return str;
        }
    }
}

Implementace indexeru je podobná vlastnosti (property) třídy, je uveden klíčovým slovem this a parametrizovaný jako pole s jedním či více indexy (v tomto případě pouze jedním pojmenovaným index typu int). Indexery můžeme také přetěžovat.

Použití

Program.cs

using System;

namespace CSharpIndexer
{
    class Program
    {
        static void Main(string[] args)
        {
            ClassArray ca = new ClassArray();

            ca["name"] = "John";
            ca["surname"] = "Johnes";
            ca["city"] = "New York";

            string dump = ca.Dump();

            Console.WriteLine(dump);
            Console.ReadLine();
        }
    }
}

A výstup z aplikace:

Stáhnout

Leave a Reply