【发布时间】:2010-02-04 00:51:11
【问题描述】:
我试图通过将其包装在一个循环中来压缩它:
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;
}
我的第一直觉是做这样的事情:
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;
}
}
但是我当然会收到错误消息:
Cannot assign to 'coord' because it is a 'foreach iteration variable'
有什么方法可以将这段代码包装在一个循环中?或者可能不值得付出努力,保留第一种形式更具可读性。
对于那些好奇的人:是的,这是实现环绕。
【问题讨论】:
-
pos.Y = bounds.Width - pixelRadius不应该是bounds.Height吗? -
这段代码是否正确?当离开左边界和 v.v. 时,它似乎迫使点跳到右边界。如果你想要模数学,为什么不使用 % 而不是 if?
-
@John:我认为你是对的。看起来他正在尝试实现环绕。
-
好的,我添加了一个模数数学答案。
-
尊重问题 title,这里有一个来自未来的相关回答链接:stackoverflow.com/questions/9780584/…