简体   繁体   中英

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:

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. therefore the Cursor Position is still set as 5 5 writing the 'X' in the same place every key stroke.

So, how does one change the value of int num01 in Class02?

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:

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:

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 .

错误是,在每个单独的调用中,您都会创建一个带有初始值的class01新实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM