C#/ .NET 4.0中的一个新功能是,您可以在foreach不获取异常的情况下更改您的枚举.请参阅Paul Jackson的博客文章"并发的有趣副作用:在枚举时从集合中删除项目"以获取有关此更改的信息.
执行以下操作的最佳方法是什么?
foreach(var item in Enumerable)
{
foreach(var item2 in item.Enumerable)
{
item.Add(new item2)
}
}
Run Code Online (Sandbox Code Playgroud)
通常我使用IList一个缓存/缓冲区直到结束foreach,但是有更好的方法吗?
考虑一下:
List<MyClass> obj_list = get_the_list();
foreach( MyClass obj in obj_list )
{
obj.property = 42;
}
Run Code Online (Sandbox Code Playgroud)
'obj'是对列表中相应对象的引用,这样当我更改属性时,更改将在构造到某处的对象实例中持续存在吗?
为什么赋值运算符(=)在foreach循环中无效?我正在使用C#,但我认为该参数对于其他支持的语言foreach(例如PHP)是相同的.例如,如果我这样做:
string[] sArray = new string[5];
foreach (string item in sArray)
{
item = "Some assignment.\r\n";
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误,"无法分配给'item',因为它是'foreach迭代变量'."
为什么foreach循环只读?我的意思是你可以获取数据,但不能增加++或减少 - .它背后的任何原因?是的我是初学者:)
〔实施例:
int[] myArray={1,2,3};
foreach (int num in myArray)
{
num+=1;
}
Run Code Online (Sandbox Code Playgroud) string newName = "new name";
int[] numbers = new int[] { 1, 2, 3 };
var people = numbers.Select(n => new Person()
{
Name = n.ToString()
});
foreach (var person in people)
{
person.Name = newName;
}
Debug.WriteLine(people.First().Name == newName); // returns false
Run Code Online (Sandbox Code Playgroud)
我期望上面的行返回true.为什么我不能在foreach循环中设置迭代变量的属性?
我声明了一个Dictionary类型对象,并尝试在其中添加一些项目.但我甚至不能修改项目的价值.密钥不应该是可修改的,但为什么不是值?谢谢.
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("1", "bob");
dict.Add("2", "jack");
dict.Add("3", "wtf");
foreach (string key in dict.Keys)
{
dict[key] = "changed"; //System.InvalidOperationException: Collection was modified
}
Run Code Online (Sandbox Code Playgroud) namespace MyNamespace
{
public struct MyStruct
{
public string MyString;
public int MyInt;
public bool MyBool;
}
public class MyClass
{
private List<MyStruct> MyPrivateVariable;
public List<MyStruct> MyVariable
{
get
{
if (MyPrivateVariable == null)
{
MyPrivateVariable = new List<MyStruct>();
MyPrivateVariable.Add(new MyStruct());
MyPrivateVariable.Add(new MyStruct());
}
return MyPrivateVariable;
}
}
public void MyLoop()
{
foreach (MyStruct ms in MyVariable)
{
// Doesn't compile, but it works if you execute it through the Immediate window, or in Quickwatch
ms.MyBool = false;
// Compiles, …Run Code Online (Sandbox Code Playgroud) 众所周知,在C#中迭代一些IEnumerable时,不能对可枚举集合的元素进行修改:
// Illegal code
foreach (Employee e in employeeList)
{
e.Salary = 1000000;
}
Run Code Online (Sandbox Code Playgroud)
我想知道运行时或枚举器本身是如何强制执行的?