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 declaration. 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
如果您完全使用数组,则可以在数组周围编写一个简单的包装类,并使用只读索引器访问元素。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.