簡體   English   中英

如何使用 C# 上的 Costum 對象創建 arrayList

[英]How to create an arrayList using Costum objects on C#

我想在動態列表中添加對象以便在其他情況下使用它,我是 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 列表。

將您的 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;
        }
    }

這樣您就可以使用 object 通過 get 方法訪問 prix、name 和數量。

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

此處的 cls[0] 正在訪問通用列表中的第一個 object。

當列表中有更多對象時,只需使用 foreach 循環進行迭代

你在找這樣的東西嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM