如何在C#中的多个变量中插入相同的值?
我有很多int变量,blueBallVelocityX1,blueBallVelocityX2,blueBallVelocityX3,blueBallVelocityX4,blueBallVelocityX5,blueBallVelocityX6,blueBallVelocityX7,blueBallVelocityX8,blueBallVelocityX9,blueBallVelocityX10,blueBallVelocityX11,blueBallVelocityX12,blueBallVelocityX13,blueBallVelocityX14,blueBallVelocityX15,blueBallVelocityX16、blueBallVelocityX17、blueBallVelocityX18、blueBallVelocityX19、blueBallVelocityX20和blueBallVelocityY1(1-20)。我需要指定所有值为5的变量。我该怎么办?您似乎在寻找多维数组:如何在C#中的多个变量中插入相同的值?,c#,variables,C#,Variables,我有很多int变量,blueBallVelocityX1,blueBallVelocityX2,blueBallVelocityX3,blueBallVelocityX4,blueBallVelocityX5,blueBallVelocityX6,blueBallVelocityX7,blueBallVelocityX8,blueBallVelocityX9,blueBallVelocityX10,blueBallVelocityX11,blueBallVelocityX12,blueBallV
int[,] blueBallVelocity = new int[2,20];
for (int x = 0; x < 2; x++)
for (int y = 0; y < 20; y++)
blueBallVelocity[x, y] = 5;
您应该考虑使用集合,例如: 我有两个选择
var blueBallVelocity = new int[20];
for (var i = 0; i < blueBallVelocity.Length; i++) {
blueBallVelocity[i] = 5;
}
var blueballvocity=newint[20];
对于(var i=0;i
像这样
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) });
}
公开课舞会
{
公共颜色{get;set;}
公共点位置{get;set;}
公共向量2D速度{get;set;}
}
var balls=新列表(20);
对于(int i=0;i<20;i++)
{
添加(新球{位置=新点(5,5)});
}
你的问题是个谜。也许这有助于了解您的尝试。或者只使用一个“我不使用多维数组”。对于blueBallVelocityX1(1-20)和blueBallVelocityY1(1-20),我想将其值设置为3。@ElaineHarden-是的,您没有使用多维数组。问题是为什么。因为在您描述您的问题时,使用多维数组比使用许多非常相似的变量要好得多。是否确实可以使用反射设置局部变量值?我遇到一个错误,无法使用[]应用索引对于int类型的表达式。我可以知道它有什么问题吗?听起来像是您试图访问int类型的元素,而不是int数组
int blueBallVelocityX1 = 5;
//...
int blueBallVelocityX20 = 5;
var blueBallVelocity = new int[20];
for (var i = 0; i < blueBallVelocity.Length; i++) {
blueBallVelocity[i] = 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) });
}