如何添加到结构数组中

Lic*_*tia 2 c# arrays

添加到数组中我遇到了麻烦.我创建了一个名为Products的类:

public struct newProducts
{
    public string productBrand;
    public string productType;
    public string productName;
    public string productFlavour;
    public int productSize;
}

//Create an array of type newProducts
newProducts[] productList = new productList[];
Run Code Online (Sandbox Code Playgroud)

而且我创建了一个函数:

public newProducts AddProduct(string brand, string type, string name, string flavour, int size)
{
    //I don't know what to do here..

    return productList;
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是将品牌,类型,名称,风味和大小值附加并存储到数组中

基本上我第一次调用这个函数时,我会输入这些值并将其存储到索引0,在第二次调用时它会将它们添加到索引1.

这可能吗?

Yuv*_*kov 5

你最好用a List<T>而不是a T[].这样,您可以随时附加值,而无需担心自己调整数组大小

List<NewProduct> products = new List<NewProduct>();
products.Add(new Product { /* more code here */ });
Run Code Online (Sandbox Code Playgroud)

此外,您可能来自较低级别的编程背景,但正如其他人所提到的,我不确定您是否真正了解structC#的真正含义.通过查看您的代码,您正在寻找class:

public class NewProduct
{
    public string ProductBrand { get; set; }
    public string ProductType { get; set; }
    public string ProductName { get; set; }
    public string ProductFlavour { get; set; }
    public int ProductSize { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我建议你通过阅读启动类和结构(MSDN)什么是结构和类在.NET之间的区别?