简体   繁体   English

C#列表框,参数

[英]C# listbox,params

As Andrew Hare suggested in his answer : 正如安德鲁·黑尔Andrew Hare)回答中所建议的:

Create a field to store all the ListBox instances and then change the constructor to accept an arbitrary number of them. 创建一个字段来存储所有ListBox实例,然后更改构造函数以接受任意数量的实例。

I tried the following 我尝试了以下

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);

How can i access listbox1? 我如何访问listbox1?

In class scaner i'm trying to call this.listBoxes. 在类扫描器中,我试图调用this.listBoxes.
(I need to call the listbox1 in scaner class.How can i do/call it? (我需要在扫描程序类中调用listbox1。我该如何做/调用它?

Thanks for answers. 感谢您的回答。

Why don't you store the array of listboxes as... an array? 为什么不将列表框数组存储为...数组?

public scanner
{
   private ListBox[] listboxes;

   public scanner(params ListBox[] listboxes)
   {
       this.listboxes = listboxes;
   }
}

Now you can access listbox1 in the call new scanner(listbox1, listbox2) as listboxes[0] in your scanner class. 现在,您可以在扫描仪类中以new scanner(listbox1, listbox2) listboxes[0]身份访问new scanner(listbox1, listbox2)调用的new scanner(listbox1, listbox2)中的new scanner(listbox1, listbox2)

I might be off, but it looks like, from your other question, that you have five ListBox 's that each have a different meaning, and you might do something special with each one. 我可能不满意,但从另一个问题来看,您似乎有五个ListBox ,每个都有不同的含义,并且您可能会对每个ListBox做一些特殊的事情。 Instead of passing them all in on the constructor, and rely on them all to be in the right order, you might want to pass in an array of KeyValuePair<object,ListBox> . 您可能希望传递一个KeyValuePair<object,ListBox>数组,而不是将它们全部传递给构造函数并依赖它们以正确的顺序传递。 Then get at each with the key you assign. 然后使用您分配的密钥获取每个密钥。

I wouldn't rely on passing an params array in with a specific order. 我不会依赖于以特定顺序传递params数组。 If you're going to need to do something very specific with the first one, and the second, etc. 如果您需要对第一个和第二个进行非常特定的操作,等等。

I might be making too many assumptions from the other question though. 不过,我可能会根据另一个问题做出过多的假设。

You can use this property, something like this... 您可以使用this属性,例如:

public class Scanner
{
    private readonly ListBox[] _listboxes;

    public Scanner(params ListBox[] listboxes)
    {
        _listboxes = listboxes;
    }

    public ListBox this[int index]
    {
        get
        {
            if(index < 0 || index > _listboxes.Length - 1) 
                throw new IndexOutOfRangeException();
            return _listboxes[index];
        }
    }
}

Usage: 用法:

ListBox listbox1 = new ListBox();
ListBox listbox2 = new ListBox();
var lst = new Scanner(listbox1, listbox2);
var lstbox1 = lst[0];

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

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