I have many int variables, blueBallVelocityX1, blueBallVelocityX2, blueBallVelocityX3, blueBallVelocityX4, blueBallVelocityX5, blueBallVelocityX6, blueBallVelocityX7, blueBallVelocityX8, blueBallVelocityX9, blueBallVelocityX10, blueBallVelocityX11, blueBallVelocityX12, blueBallVelocityX13, blueBallVelocityX14, blueBallVelocityX15, blueBallVelocityX16, blueBallVelocityX17, blueBallVelocityX18, blueBallVelocityX19, blueBallVelocityX20 and blueBallVelocityY1 (1- 20)。我需要指定值为 5 的所有变量。我该怎么做?
问问题
121 次
5 回答
6
您应该考虑使用集合,例如数组:
const int VelocityLength = 20;
const int InitialVelocity = 5;
int[] blueBallVelocityX = new int[VelocityLength];
int[] blueBallVelocityY = new int[VelocityLength];
for (int i = 0; i < VelocityLength; i++)
{
blueBallVelocityX[i] = blueBallVelocityY[i] = InitialVelocity;
}
或者:
int[] blueBallVelocityX = Enumerable.Repeat(InitialVelocity, VelocityLength).ToArray();
于 2013-07-23T08:11:11.850 回答
1
您似乎正在寻找一个多维数组:
int[,] blueBallVelocity = new int[2,20];
for (int x = 0; x < 2; x++)
for (int y = 0; y < 20; y++)
blueBallVelocity[x, y] = 5;
或 s 的一维数组Point
:
Point[] blueBallVelocity = new Point[20];
for (int i = 0; i < blueBallVelocity.Length; i++)
blueBallVelocity[i] = new Point(5, 5);
于 2013-07-23T08:11:11.280 回答
1
像这样
blueBallVelocityX1 = 5;
blueBallVelocityX2 = 5;
// ...
blueBallVelocityX20 = 5;
你应该做的更像是这样
public class Ball
{
public Color Color { get; set; }
public Point Location { get; set; }
public Vector2D Velocity { get; set; }
}
var balls = new List<Ball>(20);
for(int i = 0; i < 20; i++)
{
balls.Add(new Ball { Location = new Point(5, 5) });
}
于 2013-07-23T08:22:30.677 回答
0
我看到两个选项
- 将它们放入数组而不是制作许多变量。
- 如果上述点无法实现,请使用反射。
于 2013-07-23T08:11:41.773 回答
0
int blueBallVelocityX1 = 5;
//...
int blueBallVelocityX20 = 5;
或者,如果您厌倦了写这么多行,请将 blueBallVelocity 重新定义为一个数组:
var blueBallVelocity = new int[20];
for (var i = 0; i < blueBallVelocity.Length; i++) {
blueBallVelocity[i] = 5;
}
于 2013-07-23T08:12:22.123 回答