简体   繁体   中英

How to make an array of objects visible to other functions

In my current program I am building an array of objects and then populating it, however I need to then access this populated array from another function within the same class. In CI would do this by making the array global, but global variables dont exist in C# and when I try to use the "Static" parameter it says arrays cant be static.

namespace FormsTest1
{
    public partial class Form1 : Form
    {
        public int AppCount;
        public static applications[] appList;

        public Form1() //Main Entry point of program
        {
            IEnumerable<int> apps = VolumeMixer.EnumerateApplications();
            AppCount = apps.Count();
            int i = 0;
            applications[] appList = new applications[AppCount];
            foreach (int app in apps)
            {
                appList[i] = new applications();
                appList[i].setProcessID(app);
                appList[i].populate();
                i++;
            }
            for (int j = 0; j < AppCount; j++) { ChannelSelect1.Items.Add(appList[j].Name); }
        }

        private void ChannelSelect1_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int k = 0; k < AppCount; k++)
            {
            if (ChannelSelect1.Text == appList[k].Name) //<-- This array is not the one I populate in Form1()
            { Channels[0] = appList[k].PID; }
        }
    }

    public class applications
    {
        public int PID;
        public string ProcessName;
        public string WindowName;
        public string Name;
        public string Path;

        public void setProcessID(int ID) { PID = ID; }

        public string getProcessName() { return ProcessName; }
        public string getWindowName() { return WindowName; }
        public string getName() { return Name; }
        public string getPath() { return Path; }

        public void populate()
        {
            //stuff
        }
    }
}   

I cant pass the array into the other functions cause they are event driven, and I need the index-ability of arrays.

How do I declare and populate an array of objects in one function, and then use that array in another function in the same class?

Change your constructor from

applications[] appList = new applications[AppCount];

to

appList = new applications[AppCount];

You should initialize your instance field instead of creating a new local one.

Btw: It is not necessary to make the array static.

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