简体   繁体   English

如何使对象数组对其他功能可见

[英]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. 在CI中,可以通过使数组成为全局数组来做到这一点,但是C#中不存在全局变量,当我尝试使用“静态”参数时,它表示数组不能为静态。

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. 顺便说一句:不必使数组静态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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