[英]C# How to change an int variable from one class in another
So in this code block from my console application, when ran, should move the 'X' in Class02 up and down when you hit the respective arrow keys but it doesn't, it just stays in place: 因此,在运行我的控制台应用程序的此代码块中,当您按下相应的箭头键时,应在Class02中上下移动“ X”,但实际上并没有,只是停留在原位:
class Program
{
static void Main(string[] args)
{
Class01.Function01();
}
}
class Class01
{
public int num01 = 5;
public int num02 = 5;
public static void Function01()
{
while (true)
{
Class02.Function02();
}
}
}
class Class02
{
public static void Function02()
{
var c1 = new Class01();
Console.SetCursorPosition(c1.num02, c1.num01);
Console.Write("X");
ConsoleKeyInfo keyInfo;
keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.UpArrow:
c1.num01--;
break;
case ConsoleKey.DownArrow:
c1.num01++;
break;
}
}
}
I know what's wrong here, the int in Class01 is not being changed in class02. 我知道这里出了什么问题,Class01中的int未被更改。 therefore the Cursor Position is still set as 5 5 writing the 'X' in the same place every key stroke.
因此,光标位置仍设置为5 5,每次击键都在同一位置写入“ X”。
So, how does one change the value of int num01 in Class02? 那么,如何更改Class02中int num01的值?
Thanks for any help with this. 感谢您对此的任何帮助。
You are always creating a new instance of Class01
in the static method Class02.Function02
, therefore the value is always it's default value 5. You could make the numbers static too or you could hold a static instance variable of Class01
in Class02
, for example: 您总是在静态方法
Class02.Function02
创建Class01
的新实例,因此该值始终是默认值5。您也可以使数字静态,也可以在Class01
中Class02
的静态实例变量,例如:
class Class02
{
private Class01 c1 = New Class01();
public static void Function02()
{
Console.SetCursorPosition(c1.num02, c1.num01);
Console.Write("X");
ConsoleKeyInfo keyInfo;
keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.UpArrow:
c1.num01--;
break;
case ConsoleKey.DownArrow:
c1.num01++;
break;
}
}
}
another option is to pass the instance of Class01
to the method: 另一个选择是将
Class01
的实例Class01
给方法:
public static void Function02(Class01 c1)
{
Console.SetCursorPosition(c1.num02, c1.num01);
Console.Write("X");
ConsoleKeyInfo keyInfo;
keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.UpArrow:
c1.num01--;
break;
case ConsoleKey.DownArrow:
c1.num01++;
break;
}
}
then you call it in this way: 然后以这种方式调用它:
Class01 c1 = new Class01();
while (true)
{
Class02.Function02(c1);
}
If the calling method Function01
would not be static you could pass this
. 如果调用方法
Function01
不是静态的,则可以传递this
。
错误是,在每个单独的调用中,您都会创建一个带有初始值的class01新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.