foreach循环如何与2d数组工作?



大家好,我是c#新手。我正在尝试建立一些测试程序,我正在建立一个类似汽车商店的东西。我希望在我的节目中只显示品牌。但是当我用foreach循环写它的时候,它也需要第二个数组…如果有人能帮我理解foreach循环是如何工作的,那将是完美的:)

class CarsNum
{
public const int carsNum = 10;
}
class CarsBrands : CarsNum
{
public string[,] carsBrand = new string[carsNum,carsNum];
public int carCostArrayInt;
public void carsBrands()
{
carsBrand[0, 0] = "Ford"; carsBrand[0, 1] = "Chevrolet"; carsBrand[0, 2] = "Dodge";
carsBrand[0, 3] = "Fiat";

carsBrand[1, 0] = "120,000$"; carsBrand[1, 1] = "100,000$"; carsBrand[1, 2] = "140,000$";
carsBrand[1, 3] = "50,000$";
foreach (string i in carsBrand)
{
Console.WriteLine(i);
}
}
}

对于多维数组应该使用for循环。

for (int i = 0; i < carsBrand.GetLength(1); i++)
{
Console.WriteLine(carsBrand[0,i]);
}

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays

2D字符串数组不是您的任务的最佳选择("用汽车建立一个商店")。c#是面向对象的语言,所以你可以有一个Car类,和一个带有汽车列表的Store类——易于构建、维护和修改:

public class Car
{
public string Brand { get; set; }
public double Price { get; set; }
public int Year { get; set; } // new Car property
}
public class CarStore
{
public IList<Car> Cars { get; } = new List<Car>();
}

则使用for环或foreach-两者都可以

public static void Main()
{
var store = new CarStore
{
Cars = 
{
new Car { Brand = "Ford", Year = 2021, Price = 120000 },
new Car { Brand = "Chevrolet", Year = 2020, Price = 100000 },
}
};
foreach(var car in store.Cars)
{
Console.WriteLine(car.Price.ToString("C"));
}
// new car arrived:
store.Cars.Add(new Car { Brand = "Rolls-Royce", Year = 2022, Price = 1_000_000 });
}

相关内容

  • 没有找到相关文章

最新更新