-2
    struct process
    {
        public int Proc_Id;
        public int Proc_BurstTime;
        public int Proc_Priority;
    };

    readonly process[] ProcessList = new process[]
    {
        new process{ Proc_Id = 1, Proc_BurstTime = 3000, Proc_Priority = 1},
        new process{ Proc_Id = 2, Proc_BurstTime = 5000, Proc_Priority = 2},
        new process{ Proc_Id = 3, Proc_BurstTime = 1000, Proc_Priority = 3},
        new process{ Proc_Id = 4, Proc_BurstTime = 10000, Proc_Priority = 4}
    };

    private void Form1_Load(object sender, EventArgs e)
    {
        initial_ProcessList.Items.AddRange(ProcessList);
    }

这是我得到的错误:

The best overloaded method match for 'System.Windows.Forms.ListBox.ObjectCollection.AddRange(System.Windows.Forms.ListBox.ObjectCollection)' has some invalid arguments

Argument 1: cannot convert from 'OS450_Proj1.Form1.process[]' to 'System.Windows.Forms.ListBox.ObjectCollection'

我知道它看起来不喜欢那种数组,但是有什么办法可以填充列表框吗?如果也是因为没有字符串或任何东西可以“打印”到列表中,我是否需要将字符串值添加到结构中并为数组(ProcessList)中的所有值初始化它?如果是这样,添加到列表框时我该怎么做?

4

2 回答 2

1

是的,您不能将 somearray 转换为 object[]. ListBox.Items.AddRange需要将对象数组作为参数传递。

尝试这个

initial_ProcessList.Items.AddRange(ProcessList.Cast<object>().ToArray());

或这个

object[] ProcessList = new object[]
{
    new process{ Proc_Id = 1, Proc_BurstTime = 3000, Proc_Priority = 1},
    new process{ Proc_Id = 2, Proc_BurstTime = 5000, Proc_Priority = 2},
    new process{ Proc_Id = 3, Proc_BurstTime = 1000, Proc_Priority = 3},
    new process{ Proc_Id = 4, Proc_BurstTime = 10000, Proc_Priority = 4}
};

或者只是循环并添加

foreach (var p in ProcessList)
{
    initial_ProcessList.Items.Add(p);
}
于 2013-09-17T13:59:26.423 回答
0

首先是错误,如果该方法期望 aobject[]它不能process[]为此采取 a 。现在,如果您尝试以下操作:

initial_ProcessList.Items.AddRange(ProcessList.Cast<object>().ToArray());

错误会消失,但ListBox项目将如下所示:

WindowForm.ApplicationName.process1
WindowForm.ApplicationName.process1
.....

这是默认ToString()实现。所以你的实际问题是在ListBox. 你必须重写ToString方法。喜欢:

struct process
{
    public int Proc_Id;
    public int Proc_BurstTime;
    public int Proc_Priority;

    public override string ToString()
    {
        return string.Format("{0}, {1}, {2}", Proc_Id, Proc_BurstTime, Proc_Priority);
    }
};

DataSource稍后如果使用属性而不是添加对象数组会更简单,所以只需执行以下操作:

initial_ProcessList.DataSource = ProcessList;

这将显示结果为:

在此处输入图像描述

您还可以设置您DisplayMemberValueMember属性,ListBox但它需要您的结构具有属性,而不是字段。所以你必须修改你struct的:

struct process
{
    public int Proc_Id { get; set; }
    public int Proc_BurstTime { get; set; } //auto implemented properties
    public int Proc_Priority;

};

接着:

initial_ProcessList.ValueMember = "Proc_Id";
initial_ProcessList.DisplayMember = "Proc_BurstTime";
initial_ProcessList.DataSource = ProcessList;

这只会显示Proc_BurstTime,并且在选择时您将获得相关的值Proc_Id

于 2013-09-17T14:07:12.977 回答