开发者

How can I declare a non-writable array in C#?

开发者 https://www.devze.com 2023-01-26 09:00 出处:网络
Currently, my code resembles this: private static readonly int[] INTARRAY = {1, 2, 3}; This prevents me from assigning to INTARRAY to a new instance of int[] outside of the static constructor, but

Currently, my code resembles this:

private static readonly int[] INTARRAY = {1, 2, 3};

This prevents me from assigning to INTARRAY to a new instance of int[] outside of the static constructor, but it still allows me to assign to the individual int elements.

For example:

INTARRAY[1] = 5;

How can I make this array completely read-only? This is an array of value-types, and is assigned with an array initializer in the de开发者_JS百科claration. How can I make these initial values persist indefinitely?


If it's an array, you can't. But if you're willing for it to be an IList<int>, you can do:

private static readonly IList<int> INTARRAY = new List<int> {1, 2, 3}.AsReadOnly();


unfortunately, there is no builtin c# construct that provides this feature for arrays. Best solution is to use a List instead if it conforms with your business needs


If you're absolutely set on using an array, you could write a simple wrapper class around the array with a read-only indexer accessing the elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号