c# - 为什么将列表转换为数组而不是在 c# 中引用?
问题描述
.Net 中的数组是引用类型。给定上面的两个代码段。问题:为什么设置值变量“fixedItem”影响第一段代码中的变量“数据”,但第二段代码不影响
第一个代码段:
var data = new List<IList<int>>();
data.Add(new List<int>() { 1, 2, 3 });
data.Add(new List<int>() { 3, 8, 6,5 });
data.Add(new List<int>() { 1, 2 });
var fixedItem = data.Last();
fixedItem[1] = 8;
//Result:
//data = {{1,2,3}, {3,8,6,5}, {1,8}}
第二段代码:
var data = new List<IList<int>>();
data.Add(new List<int>() { 1, 2, 3 });
data.Add(new List<int>() { 3, 8, 6,5 });
data.Add(new List<int>() { 1, 2 });
var fixedItem = data.Last().ToArray();
fixedItem[1] = 8;
//Result:
//data = {{1,2,3}, {3,8,6,5}, {1,2}}
解决方案
根据文档 list.ToArray() 方法返回带有原始列表副本的数组
推荐阅读
- android - 如何使用拦截器更改@Query 参数?
- kotlin - Kotlin - SQLiteDatabase - 不确定如何让列文本显示在 ViewHolder 中
- python - Python-docx用连续编号替换字符串
- excel - 如何修改 Google 应用脚本以从 2 列而不是 1 列搜索并在两列匹配时返回整行?
- sql - 如何避免 SQL 中 SELECT、GROUP BY 和 ORDER BY 中的函数重复
- node.js - 如何在 Twilio 无服务器功能中将 googleapis google.auth.GoogleAuth() 用于 google API 服务帐户?
- amazon-web-services - AWS 在创建快照时如何处理更改(EBS 和 EC2 实例)?
- typeorm - 如何使用 createQueryBuilder 中的自定义存储库方法?
- java - 如何修复以下_CastError被抛出构建:类型'Future
' 不是类型 'List 的子类型 ' 在类型转换中 - c# - LibVLC:在 LibVLC 中是否有像 v360:fisheye 这样的过滤器?