gpt4 book ai didi

c# - 是否可以在 C# 中将数组声明为只读?

转载 作者:太空狗 更新时间:2023-10-30 00:19:25 33 4
gpt4 key购买 nike

是否可以将一个数组设为只读。这样就不允许将值设置为数组。

这里我尝试使用 readonly 关键字来声明数组。然后我通过使用 IsReadOnly 属性检查该数组是否只读。但它永远不会返回 true。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PrivateExposeConsoleApp
{
class Program
{
private static readonly int[] arr = new int[3] { 1,2,3 };

static void Main(string[] args)
{
// Create a read-only IList wrapper around the array.
IList<int> myList = Array.AsReadOnly(arr);

try
{
// Attempt to change a value of array through the wrapper.
arr[2] = 100;
Console.WriteLine("Array Elements");
foreach (int i in arr)
{
Console.WriteLine("{0} - {1}", i + "->", i);
}
Console.WriteLine("---------------");
Console.WriteLine("List Elements");
foreach (int j in myList)
{
Console.WriteLine("{0} - {1}", j + "->", j);
}
// Attempt to change a value of list through the wrapper.
myList[3] = 50;
}
catch (NotSupportedException e)
{

Console.WriteLine("{0} - {1}", e.GetType(), e.Message);
Console.WriteLine();
}



//if (arr.IsReadOnly)
//{
// Console.WriteLine("array is readonly");
//}
//else
//{
// for (int i = 0; i < arr.Length; i++)
// {
// arr[i] = i + 1;
// }

// foreach (int i in arr)
// {
// Console.WriteLine(i);
// }
//}

Console.ReadKey();
}
}
}

这里看我的评论部分。如果我取消注释,我的 arr 永远不会变成只读的。在声明中,我明确地将 arr 定义为只读,数据为 {1,2,3}。我不希望这个值被重写。它应该始终只有 1、2、3。

最佳答案

数组本质上是可变的,要获得您想要的行为,您需要使用包装器 ReadOnlyCollection<T> .您可以使用 arr.AsReadOnly() 创建数组的只读副本

关于c# - 是否可以在 C# 中将数组声明为只读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20589627/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com