相关疑难解决方法(0)

为什么C#foreach语句中的迭代变量是只读的?

据我了解,C#的foreach迭代变量是不可变的.

这意味着我不能像这样修改迭代器:

foreach (Position Location in Map)
{
     //We want to fudge the position to hide the exact coordinates
     Location = Location + Random();     //Compiler Error

     Plot(Location);
}
Run Code Online (Sandbox Code Playgroud)

我无法直接修改迭代器变量,而是必须使用for循环

for (int i = 0; i < Map.Count; i++)
{
     Position Location = Map[i];
     Location = Location + Random();

     Plot(Location);        
     i = Location;
}
Run Code Online (Sandbox Code Playgroud)

来自C++背景,我认为foreach是for循环的替代品.但是由于上述限制,我通常会回退使用for循环.

我很好奇,使迭代器不可变的原理是什么?


编辑:

这个问题更多的是一个好奇的问题,而不是一个编码问题.我很欣赏编码答案,但我不能将它们标记为答案.

此外,上面的例子过于简化了.这是我想要做的C++示例:

// The game's rules: 
//   - The "Laser Of Death (tm)" moves around the game board from the
//     start area (index …
Run Code Online (Sandbox Code Playgroud)

c# language-design

35
推荐指数
3
解决办法
2万
查看次数

为什么赋值运算符(=)在foreach循环中无效?

为什么赋值运算符(=)在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迭代变量'."

c# foreach variable-assignment

26
推荐指数
3
解决办法
2万
查看次数

如何用C#在字符串中用"https:"替换"http:"?

我已经使用"http://"将所有网址存储在我的应用程序中 - 我现在需要通过"https:"替换所有网址.现在我有:

    foreach (var link in links)
        {
            if (link.Contains("http:"))
            {
                /// do something, slice or replace or what?
            }
        }
Run Code Online (Sandbox Code Playgroud)

我只是不确定更新字符串的最佳方法是什么.如何才能做到这一点?

c#

0
推荐指数
2
解决办法
5471
查看次数