Real world use cases for C# indexers?

后端 未结 14 1516
时光说笑
时光说笑 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 15:53

    Microsoft has an example using an indexer to treat a file as an array of bytes.

    public byte this[long index]
    {
        // Read one byte at offset index and return it.
        get 
        {
            byte[] buffer = new byte[1];
            stream.Seek(index, SeekOrigin.Begin);
            stream.Read(buffer, 0, 1);
            return buffer[0];
        }
        // Write one byte at offset index and return it.
        set 
        {
            byte[] buffer = new byte[1] {value};
            stream.Seek(index, SeekOrigin.Begin);
            stream.Write(buffer, 0, 1);
        }
    }
    

提交回复
热议问题