Read-only array in .NET

前端 未结 2 713
庸人自扰
庸人自扰 2020-12-18 11:11

Arrays are a fast way to iterate through an unordered set of items, and it\'s often nice for them to be read-only. While exposing arrays with the `readonly\' keyword is use

相关标签:
2条回答
  • 2020-12-18 11:49

    I think the below does what you want. However, I think this is actually inadvisable. You're imposing an unnecessary and potentially confusing abstraction. Yes, the JIT will probably optimize it eventually, and your coworkers should catch on. But you're still doing something the language isn't meant to do.

    EDIT: I've tweaked and better explained the below code, and mentioned a couple of options.

    using System.Collections;
    using System.Collections.Generic;
    
    /*
      You can leave off the interface, or change to IEnumerable.  See below.
    */
    class ReadOnlyArray<T> : IEnumerable<T>
    {
        private readonly T[] array;
    
        public ReadOnlyArray(T[] a_array)
        {
            array = a_array;
        }
    
        // read-only because no `set'
        public T this[int i]
        { get { return array[i]; } }
    
        public int Length
        { get { return array.Length; } }
    
        /* 
           You can comment this method out if you don't implement IEnumerable<T>.
           Casting array.GetEnumerator to IEnumerator<T> will not work.
        */
        public IEnumerator<T> GetEnumerator()
        {
            foreach(T el in array)
            {
                yield return el;
            }
        }
    
        /* 
           If you don't implement any interface, change this to:
           public IEnumerator GetEnumerator()
    
           Or you can implement only IEnumerable (rather than IEnerable<T>)
           and keep "IEnumerator IEnumerable.GetEnumerator()"
        */
        IEnumerator IEnumerable.GetEnumerator()
        {
            return array.GetEnumerator();
        }
    }
    
    0 讨论(0)
  • 2020-12-18 11:50

    Arrays are a fast way to iterate through an unordered set of items,

    If that's all you need to do, just return the array as an IEnumerable. Don't implement IEnumerable yourself: the array already does that.

    That should meet all three of your goals.

    public class SomeClass
    { 
        private T[] myArray; // T could be any type
    
        public IEnumerable<T> MyReadOnlyArray { get { return myArray; } }
    }
    
    0 讨论(0)
提交回复
热议问题