【发布时间】:2022-06-16 23:43:31
【问题描述】:
关于这个问题的许多主题。想知道为什么有时集合是只读的,有时不是。我在一个 netCore 3.1 项目中遇到了一个问题,其目的是在 foreach 循环中修改一个集合。问题是在迭代之后,但是集合根本没有修改......根据我的理解,这是有道理的。
public async Task DoFoo(IEnumerable<SomeClass> data, CancellationToken cancellationToken)
{
foreach (var item in data)
{
item.Id = item.SomeOtherValue;
//note: checked and Id is {get;set;}
}
await SaveData(data, cancellationToken);
}
结果是 id 仍然为空。投射到列表然后修改解决了这个问题。 然而,在 .net fiddle (https://dotnetfiddle.net/bQvf40) 上进行的测试表明该集合实际上已被更改。这真的不是我所期望的。谁能解释一下为什么会发生变化。
using System;
using System.Diagnostics;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var iePerson = new[] { new Person(){Id = 2, Name="SomeName", Other=5} }; //note other = 5
IEnumerable<Person> pien = iePerson; //writing this way to ensure we are creating IEnumable
DoFoo(pien);
}
private static void DoFoo(IEnumerable<Person> entities)
{
foreach(Person p in entities)
{
Console.WriteLine(p.Id);
p.Id = p.Other;
}
foreach(Person p in entities)
Console.WriteLine(p.Id);
//result is
//2
//5 <--- was expecting to see 2...
}
public class Person
{
public string Name {get;set;}
public int Id {get;set;}
public int Other {get;set;}
}
}
【问题讨论】:
-
p.Id = p.Other 这一行使它成为 5。对象是可变类型。可变类型,在 C# 中,是一种对象类型,其数据成员(如属性、数据和字段)在创建后可以修改。
标签: c# .net ienumerable