将数组值分配给某个变量,填充数组

时间:2013-01-28 09:51:14

标签: c#

ArrayList USStates填充了如图所示的值,但如果我想在数组中访问这些值,我该怎么做?通过USStates(1)引用不起作用。任何人都可以解释这行代码吗?

USStates.Add(new USState("Alabama", "AL"));

完整代码:

// Populate the list box using an array as DataSource.
ArrayList USStates = new ArrayList();
USStates.Add(new USState("Alabama", "AL"));
USStates.Add(new USState("Washington", "WA"));
USStates.Add(new USState("West Virginia", "WV"));
USStates.Add(new USState("Wisconsin", "WI"));
USStates.Add(new USState("Wyoming", "WY"));
ListBox1.DataSource = USStates;

// Set the long name as the property to be displayed and the short
// name as the value to be returned when a row is selected.  Here
// these are properties; if we were binding to a database table or
// query these could be column names.
ListBox1.DisplayMember = "LongName";
ListBox1.ValueMember = "ShortName";

public class USState
{
    private string myShortName;
    private string myLongName;

    public USState(string strLongName, string strShortName)
    {
        this.myShortName = strShortName;
        this.myLongName = strLongName;
    }

    public string ShortName
    {
        get
        {
            return myShortName;
        }
    }

    public string LongName
    {
        get
        {
            return myLongName;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我建议您使用Generic List来提高性能[{1}}

(Boxing unboxing, ...)

链接:http://msdn.microsoft.com/fr-fr/library/vstudio/6sh2ey19.aspx

答案 1 :(得分:1)

问题有点令人困惑/不完整,不知怎的,如果您的目的只是创建一个查找表并将其绑定到下拉列表,那么您可以这样做。

private static Hashtable LookUpIdTable = null;

然后在你的main函数中或者你想要创建一个单独的类:

            LookUpIdTable.Add("AL", "Alabama");
            LookUpIdTable.Add("AK", "Alaska");
            LookUpIdTable.Add("AS", "American Samoa");
            LookUpIdTable.Add("AZ", "Arizona");
            LookUpIdTable.Add("AR", "Arkansas");
            LookUpIdTable.Add("CA", "California");
            LookUpIdTable.Add("CO", "Colorado");
            LookUpIdTable.Add("CT", "Connecticut");

当你想要绑定时:

        DropDown.DataSource = LookUpIdTable
        DropDown.DataValueField = "Key";
        DropDown.DataTextField = "Value";
        DropDown.DataBind();