[英]How to create an arrayList using Costum objects on C#
I want to add objects on a dynamic list for use it after on other cases, I'm new on C# .net and I tried this piece of code:我想在动态列表中添加对象以便在其他情况下使用它,我是 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;
}
}
and on my main form:在我的主要形式上:
DashboardClass Object = new DashboardClass();
List<object> ProductList = new List<object>();
DashboardClass item = Object.SetInfo("ala", 152, 1);
ProductList.Add(item);
please how to modify my code for making a list of Productlist.请如何修改我的代码以制作 Productlist 列表。
Make your setinfo to constructor.将您的 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;
}
}
This way you can use object to access prix,name and quantity through get methods.这样您就可以使用 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] here is accessing the first object in the generic list.此处的 cls[0] 正在访问通用列表中的第一个 object。
When you have more objects in the list just iterate using foreach loop当列表中有更多对象时,只需使用 foreach 循环进行迭代
are you looking for something like this?你在找这样的东西吗?
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;
}
}
then然后
List<object> ProductList = new List<object>();
DashboardClass item = new DashboardClass("ala", 152, 1);
ProductList.Add(item);
or Typed way (Added according to authors comment)或打字方式(根据作者评论添加)
List<DashboardClass> ProductList = new List<DashboardClass>();
DashboardClass item = new DashboardClass("ala", 152, 1);
ProductList.Add(item);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.