从另一个类添加项目到列表 [英] Add items to list from another class

查看:76
本文介绍了从另一个类添加项目到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单独的表单/类中将项目添加到列表框时遇到了一些问题。我想要添加到列表框的数据来自网络,通过EventHandler。



我在将项目实际添加到列表框时遇到问题;我能够成功地将项目添加到字符串列表List< string>当我在EvenHandler方法中遍历列表时,项目就在那里;但是,当II循环遍历表单中的字符串列表时,不会返回任何项目。



这是主要的表单类:



I'm having some issues adding items to a listbox in a separate form/class. The data, which I want to add to the listbox, is coming from a network via an EventHandler.

I'm having issues with actually adding the items to the listbox; I'm able to successfully add the items to a string list List<string> and when I loop through the list in the EvenHandler method, the items are there; however, when I I loop through the string list in the form, no items are returned.

Here's the main form class:

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();

        foreach(string s in Utils.stringList)
        {
            listBox.Items.Add(s);

            // if I loop through the items here, nothing is returned
            foreach(string s in stringList)
            {
                Console.WriteLine(s);
            }
        }
    }
}







这里是我有EventHandler的类,其中将项添加到字符串列表中:






And here's the class that I have the EventHandler in which adds the items to the string list:

public class Utils
{
    public List<string> stringList = new List<string>();
    void ItemsReceived(object sender, DataReceivedEventArgs<RetrieveUsers> e)
    {
        stringList.Add(e.Item);

        // if I loop through the list here, the items are returned
        foreach(string s in stringList)
        {
            Console.WriteLine(s);
        }
    }
}





关于如何解决此问题的任何想法?



Any ideas on how to fix this?

推荐答案

'Utils是一个类,但在你的代码中你永远不会创建该类的实例



像这样:Utils currentUtils = new Utils();



一旦有了Class的实例,就可以访问公共列表< string> stringList



像这样(在你的主表格中):
'Utils is a Class, but in your code you never create an instance of that class.

Like this: Utils currentUtils = new Utils();

Once you have an instance of the Class, you can access the Public List<string>stringList

Like this (in your Main Form):
foreach(string receivableItem in currentUtils.stringList)
{
    listBox.Items.Add(receivableItem);
}

注意:您的EventHandler没有访问修饰符,因此默认情况下是私有访问:除非您将其设置为public或internal,否则Utils之外的任何对象都不能使用/订阅它。所以,你展示的不是代码。

Note: your EventHandler has no access modifier, and, so, is, by default, private access: unless you make it 'public, or 'internal, no object outside Utils can use/subscribe to it. So, what you show is not working code.


这篇关于从另一个类添加项目到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆