Are immutable arrays possible in .NET?

后端 未结 9 828
忘了有多久
忘了有多久 2020-12-05 23:22

Is it possible to somehow mark a System.Array as immutable. When put behind a public-get/private-set they can\'t be added to, since it requires re-allocation a

9条回答
  •  借酒劲吻你
    2020-12-05 23:48

    The Framework Design Guidelines suggest returning a copy of the Array. That way, consumers can't change items from the array.

    // bad code
    // could still do Path.InvalidPathChars[0] = 'A';
    public sealed class Path {
       public static readonly char[] InvalidPathChars = 
          { '\"', '<', '>', '|' };
    }
    

    these are better:

    public static ReadOnlyCollection GetInvalidPathChars(){
       return Array.AsReadOnly(InvalidPathChars);
    }
    
    public static char[] GetInvalidPathChars(){
       return (char[])InvalidPathChars.Clone();
    }
    

    The examples are straight from the book.

提交回复
热议问题