C#:不能分配给foreach迭代变量 [英] C#: Cannot assign to foreach iteration variable

查看:153
本文介绍了C#:不能分配给foreach迭代变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if(pos.X + pixelRadius< 0){
pos.X = bounds.Width - pixelRadius;
} else if(pos.X + pixelRadius> bounds.Width){
pos.X = pixelRadius;


if(pos.Y + pixelRadius <0){
pos.Y = bounds.Heigh - pixelRadius;
} else if(pos.Y + pixelRadius> bounds.Height){
pos.Y = pixelRadius;

$ / code>

我的第一本能是做这样的事情:

  foreach(float coord in new float [] {pos.X,pos.Y}){
float upperBound =(coord == pos .X?bounds.Width:bounds.Height);
if(coord + pixelRadius <0){
coord = upperBound - pixelRadius;
} else if(coord + pixelRadius> upperBound){
coord = pixelRadius;


$ / code $ / pre

当然然后我得到错误信息: / b>

 不能分配给'coord',因为它是'foreach迭代变量'
/ pre>

有什么办法可以将这段代码封装在一个循环中?或者不值得这样做,而且在第一种形式下可读性更高。



对于那些好奇的人来说:是的,这是实现环绕式的。

解决方案

老实说,我觉得第一个版本更具可读性。第二个版本在一个循环中批量填充,然后...测试以查看哪个循环元素是?闻起来像 ... case 反模式给我。


I'm trying to condense this by wrapping it in a loop:

       if (pos.X + pixelRadius < 0) {
            pos.X = bounds.Width - pixelRadius;
        } else if (pos.X + pixelRadius > bounds.Width) {
            pos.X = pixelRadius;
        }

        if (pos.Y + pixelRadius < 0) {
            pos.Y = bounds.Heigh - pixelRadius;
        } else if (pos.Y + pixelRadius > bounds.Height) {
            pos.Y = pixelRadius;
        }

My first instinct was to do something like this:

        foreach (float coord in new float[] { pos.X, pos.Y }) {
            float upperBound = (coord == pos.X ? bounds.Width : bounds.Height);
            if (coord + pixelRadius < 0) {
                coord = upperBound - pixelRadius;
            } else if (coord + pixelRadius > upperBound) {
                coord = pixelRadius;
            }
        }

But of course then I get the error message:

Cannot assign to 'coord' because it is a 'foreach iteration variable'

Is there any way I can wrap this code in a loop? Or maybe it's not worth the effort, and it's more readable to leave in the first form.

For those who are curious: yes, this is implementing wrap-around.

解决方案

Honestly, I think the first version is more readable. The second version batches stuff up in a loop and then ... tests to see which loop element it is??? Smells like for...case antipattern to me.

这篇关于C#:不能分配给foreach迭代变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆