如何在C#上使用Costum对象创建一个arrayList?

问题描述 投票:0回答:2

我想在动态列表中添加对象,以便在其他情况下使用它,我是C#.net的新手,我尝试了这段代码。

class DashboardClass
    {
        private int prix;
        private string name;
        private int quantity;

        public void SetInfo(string name, int prix, int quantity)
        {
            this.prix = prix;
            this.quantity = quantity;
            this.name = name;
        }

        public int getprix()
        {
            return prix;
        }
        public string getname()
        {
            return name;
        }

        public int getquantity()
        {
            return quantity;
        }
    }

并在我的主窗体上。

 DashboardClass Object = new DashboardClass();
         List<object> ProductList = new List<object>();
        DashboardClass item = Object.SetInfo("ala", 152, 1);
        ProductList.Add(item);

请问如何修改我的代码来制作Productlist的列表。

c#
2个回答
1
投票

把你的setinfo放到构造函数中。

class DashboardClass
    {
        private int prix;
        private string name;
        private int quantity;

        public DashboardClass(string name, int prix, int quantity)
        {
            this.prix = prix;
            this.quantity = quantity;
            this.name = name;
        }

        public int getprix()
        {
            return prix;
        }
        public string getname()
        {
            return name;
        }

        public int getquantity()
        {
            return quantity;
        }
    }

这样你就可以通过get方法使用对象来访问prix,name和quantity。

List<DashboardClass> cls = new List<DashboardClass>();
            cls.Add(new DashboardClass("example", 1, 1));
            Console.WriteLine(cls[0].getprix());
            Console.Read();

cls[0]这里是访问通用列表中的第一个对象。

当你的列表中有更多的对象时,只需使用 foreach 循环进行迭代。


0
投票

你在找这样的东西吗?

class DashboardClass
{
    private int prix;
    private string name;
    private int quantity;

    public void DashboardClass(string name, int prix, int quantity)
    {
        this.prix = prix;
        this.quantity = quantity;
        this.name = name;
    }

    public int getprix()
    {
        return prix;
    }
    public string getname()
    {
        return name;
    }

    public int getquantity()
    {
        return quantity;
    }
}

那么

List<object> ProductList = new List<object>();
DashboardClass item = new DashboardClass("ala", 152, 1);
ProductList.Add(item);

或打字方式 (根据提交人评论添加)

List<DashboardClass> ProductList = new List<DashboardClass>();
DashboardClass item = new DashboardClass("ala", 152, 1);
ProductList.Add(item);
© www.soinside.com 2019 - 2024. All rights reserved.