Real world use cases for C# indexers?

后端 未结 14 1523
时光说笑
时光说笑 2020-12-04 15:26

I\'ve seen lot of examples for c# Indexers, but in what way will it help me in real life situations.

I know the C# guru wouldn\'t have added this if it wasn\'t a ser

14条回答
  •  囚心锁ツ
    2020-12-04 16:08

    You can use an indexer to elegantly provide read/write multi-threading synchronization to a non-thread safe dictionary (or any non-thread safe collection):

    internal class ThreadSafeIndexerClass
    {
        public object this[int key]
        {
            get
            {
                // Aquire returns IDisposable and does Enter() Exit() on a certain ReaderWriterLockSlim instance
                using (_readLock.Aquire()) 
                {
                    object subset;
                    _dictionary.TryGetValue(key, out foundValue);
                    return foundValue;
                }
            }
            set
            {
                // Aquire returns IDisposable and does Enter() Exit() on a certain ReaderWriterLockSlim instance
                using (_writeLock.Aquire())
                    _dictionary[key] = value;
            }
        }
    }
    

    Useful especially when you don't want to use the heavyweight ConcurrentDictionary (or any other concurrent collection).

提交回复
热议问题