如何在C#中的多个变量中插入相同的值

本文关键字:插入 变量 | 更新日期: 2023-09-27 18:24:17

我有很多int变量,blueBallVelocityX1、blueBallVelicityX2、blueBallVelocityX3、blueBallVelocity X4、blueBall VelocityX5、bluebalVelocityX6、blueball VelocityX7、blue BallVelocity X8、blueBalVelocityX9、blueBallViocityX10、blueBALVelocityX11、blue巴利VelocityX12、blue鲍尔VelocityX13、blueBall天鹅绒X14、blueBall丝绒X15、BlueBallVelociityX16、blueBall速度X17,blueBallVelocityX18、blueBallVelicityX19、blueBallVelocityX20和blueBallVelcityY1(1-20)。我需要指定所有值为5的变量。我该怎么办?

如何在C#中的多个变量中插入相同的值

您应该考虑使用集合,例如数组:

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();

您似乎在寻找一个多维数组:

int[,] blueBallVelocity = new int[2,20];
for (int x = 0; x < 2; x++)
    for (int y = 0; y < 20; y++)
        blueBallVelocity[x, y] = 5;

或者PointS:的一维阵列

Point[] blueBallVelocity = new Point[20];
for (int i = 0; i < blueBallVelocity.Length; i++) 
    blueBallVelocity[i] = new Point(5, 5);

像这个

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) });
}

我看到两个选项

  1. 将它们放入数组中,而不是生成许多变量
  2. 若无法达到上述点,则使用反射
  int blueBallVelocityX1 = 5;
  //...
  int blueBallVelocityX20 = 5;

或者,如果你厌倦了写这么多行,可以将blueBallVelocity重新定义为数组:

  var blueBallVelocity = new int[20];
  for (var i = 0; i < blueBallVelocity.Length; i++) {
    blueBallVelocity[i] = 5;
  }