При вызове статического целого числа из другого класса он теряет свое значение и по умолчанию обнуляется? - PullRequest
0 голосов
/ 14 октября 2019

Я пытаюсь вызвать статическое целое число из одного класса в другой. Это целое число успешно вызывается, но значение равно нулю вместо значения из исходного класса.

Я несколько раз пытался добраться до этого момента, но сейчас застрял. Я предполагаю, что эта проблема - ошибка новичка. Любая помощь будет принята с благодарностью.

В классе 1 ...

public static int countSAO;
...
countSAO = SAO_Num.count;

после этого countSAO имеет значение 9017. В другом классе ...

button.Text = Class1.countSAO.toString();

текст кнопки равен 0 вместо ожидаемого 9017.

Большой кусок кода (Class1).

class Class1
{

public static List<String> SAO_Num = new List<String>();
... //Create the SAO lists that show up in the while loop.

public void InitializeSaoStars()
    {
...
 while ((line = fileSAO.ReadLine()) != "#End")
                {                        
                    string[] items = line.Split('\t'); //Store strings into aray.  Items seperated by tabs.
                    //Add to our lists, items[0] and items[1] are to be skipped per the file.
                    SAO_BayerLetter.Add(items[2]);
                    SAO_Constellation.Add(items[3]);
                    SAO_Num.Add(items[4]);
                    SAO_CoordRA.Add(items[5]);
                    SAO_CoordDec.Add(items[6]);
                    SAO_Magnitude.Add(items[7]);
                    SAO_SpectralType.Add(items[8]);
                    SAO_Distance.Add(items[9]);
                    SAO_ProperName.Add(items[10]);
                    SAO_AutoCalFlag.Add(items[11]);

                }
...
textBox1.Text = SAO_Num.Count.ToString();// this is 9017
...
public static int MyCountSAOValue()
    {

        return SAO_Num.Count;
    }

Это все из Class1.

Вотя вызываю метод MyCountSAOValue в Class2.

public partial class Class2: UserControl
{
    public UserControlTelescope()
    {
        InitializeComponent();
        button.Text = UserControlRotator.MyCountSAOValue().ToString();//This sets the button text to 0.

Ответы [ 4 ]

1 голос
/ 14 октября 2019

Это должно помочь вам найти порядок, в котором вызывается счет. Просто замените:

public static List<String> SAO_Num = new List<String>();

на:

 public static List<string> sao_num = new List<string>();
 public static List<string> SAO_Num {
            get {
                Console.WriteLine("Grabbing value of SAO_NUM: " + (sao_num == null ? "null" : "" + sao_num.Count));
                return sao_num;
            }
            set
            {
                Console.WriteLine("Setting value of SAO_NUM to: " + (value == null ? "null" : "" + value.Count));
                sao_num = value;
            }
        }
0 голосов
/ 14 октября 2019

class1 - это UserControl, а class2 - это форма? Вот простая демонстрация может помочь вам. Значение текста является нормальным. класс UserControlRotator

public partial class UserControlRotator : UserControl
{
    public UserControlRotator()
    {
        InitializeComponent();
    }

    static List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // 9
    public static int countSAO = list.Count;

    public static int MyCountSAOValue()
    {
        return list.Count;
    }
}

класс Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        button.Text = UserControlRotator.MyCountSAOValue().ToString(); // 9
    }
}
0 голосов
/ 14 октября 2019

Статические члены (переменные, свойства, методы) могут быть доступны напрямую. Если вы попытаетесь получить доступ к countSAO без его изменения, он вернет 0.

Вам нужно будет обновить значение перед его использованием. Вы можете использовать конструктор класса или иметь статическое свойство, которое будет обновлять его.

protected void Page_Load(object sender, EventArgs e)
{
    int beforeInstantiation = Class1.countSAO; // output: 0

    Class1 myclass = new Class1();

    int afterInstantiation = Class1.countSAO; // output: 9017

    Class1.updatedCount(); // update the Static variable before calling

    int updatedSao = Class1.countSAO; // output 500

    int saoProperty = Class1.countSAOProperty; // output 9017
}

class Class1
{
    public static int countSAO; // this would not 

    public static int countSAOProperty
    {
        get
        {
            return SAO_Num.Count;
        }
    }

    // this will be called only when the class is instantiated using New Class1();
    public static List<int> SAO_Num
    {
        get
        {
            List<int> intlist = new List<int>();

            for (int i = 0; i < 9017; i++)
            {
                intlist.Add(i);
            }

            return intlist;
        }
    }
    // this will only run if class is Instantiate using New Class();
    public Class1()
    {
        countSAO = SAO_Num.Count;
    }

    public static void updatedCount()
    {
        countSAO = 500;
    }
}
0 голосов
/ 14 октября 2019

Обновление:

Вы должны назначить текст кнопки в Class2, а не в Class1 (удалите строку в Class1, где вы также устанавливаете текст кнопки).

public static class Class1
{
    // simulate reading lines from file
    public static List<String> SAO_Num = new List<String>() {
        "test1",
        "test2",
        "test3",
        "test4",
        "test5",
        "test6",
        "test7",
        "test8",
        "test9",
        "test10"
    };

    public static int countSAO = SAO_Num?.Count ?? 0;
}

public class Class2
{
    ...
    button.Text = Class1.countSAO.ToString();
    ...
}
...