C#; listbox's as one object(container)

ぃ、小莉子 提交于 2019-12-11 05:45:44

问题


I use Visual studio 2008
I have 5 listbox's on form,I created a new class file -called him "scaner.cs"

scaner.cs -he cannot see "listbox".

I have create an instance.
scaner Comp = new scaner(listBox2, listBox1, listBox3, listBox4, listBox5);

In scaner.cs file I use it like this.

class scaner
    {
        public ListBox ls;
        public ListBox lsE;
        public ListBox lsIVars;
        public ListBox lsNumbers;
        public ListBox lsStrings;

public scaner(ListBox ls, ListBox lsE, ListBox lsIVars, ListBox lsNumbers, ListBox lsStrings)
        {
            this.ls = ls;
            this.lsE = lsE;
            this.lsIVars = lsIVars;
            this.lsNumbers = lsNumbers;
            this.lsStrings = lsStrings;
        }
}

My question : How can i replaced this big code to more "comfortably" method.

scaner Comp = new scaner(listBox2, listBox1, listBox3, listBox4, listBox5);

IF i had more then 5 listbox's ,it will be awful. How can i acced form another class file "Listbox's" Thanks for answers.


回答1:


Create a field to store all the ListBox instances and then change the constructor to accept an arbitrary number of them:

class scaner
{
    readonly IEnumerable<ListBox> listBoxes;

    public IEnumerable<ListBox> ListBoxes
    {
        get { return this.listBoxes; }
    }

    public scaner(params ListBox[] listBoxes)
    {
        this.listBoxes = listBoxes;    
    }
}

This will allow you to do this:

scaner Comp = new scaner(listBox1, listBox2);

or this:

// Here I am passing 4 ListBoxes - you can pass as many as you wish
// without modifying the source code of your scaner class
scaner Comp = new scaner(listBox1, listBox2, listBox3, listBox4);



回答2:


Use List<ListBox>



来源:https://stackoverflow.com/questions/2744332/c-listboxs-as-one-objectcontainer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!