日期:2014-05-18  浏览次数:20533 次

如何创建一个arraylist结构体数组,即元素为结构体的 arraylist
如题~~~很郁闷,数组不能达到我的要求。因为我要动态删除和插入,还有点疑问如果我用结构体作为 arraylist 的元素以后页面控件的绑定是否还是和普通数组一样处理?

------解决方案--------------------
C# code

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                List<StructTest> list = new List<StructTest>();
                list.Add(new StructTest(1, false, DateTime.Now, "Hello"));
                this.GridView1.DataSource = list;
                this.GridView1.DataBind();
            } 

        }
        struct StructTest
        {
            int a;
            public int A
            {
                get { return a; }
                set { a = value; }
            }
            bool b;

            public bool B
            {
                get { return b; }
                set { b = value; }
            }
            DateTime c;

            public DateTime C
            {
                get { return c; }
                set { c = value; }
            }
            string d;

            public string D
            {
                get { return d; }
                set { d = value; }
            }

            public StructTest(int a, bool b, DateTime c, string d)
            {
                this.a = a;
                this.b = b;
                this.c = c;
                this.d = d;
            }
        }

------解决方案--------------------
C# code

ArrayList al = new ArrayList();
al.Add(1); // 将1加入数组
al.Add(3); // 将3加入数字
al.Insert(1, 2); // 在1和3直接插入一个元素
al.Remove(3); // 删除数组中的第一个3
al.Sort(); // 给数组排序
foreach (object o in al) { 
    // 遍历整个数组
}

------解决方案--------------------
还有点疑问如果我用结构体作为 arraylist 的元素以后页面控件的绑定是否还是和普通数组一样处理?
=================
一样处理

C# code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default11 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList al = new ArrayList();
        for (int i = 0; i < 5; i++)
        {
            TestUser u = new TestUser();
            u.Name = "test"+i.ToString();
            u.ID = i;
            al.Add(u);
        }
        this.GridView1.DataSource = al;
        GridView1.DataBind();
    }

    
}

struct TestUser
{
    private string _name;
    private int _id;
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }

    public int ID
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }
}