📅  最后修改于: 2023-12-03 15:41:26.006000             🧑  作者: Mango
苦味食物是一类食物,它们有独特和强烈的苦味。这种风味可以在咖啡、啤酒、巧克力、酸奶、蔬菜等众多食物中找到。在此示例中,我们将介绍如何使用 C# 编写一个苦味食物的程序。
在开始之前,你需要做好以下准备:
我们将使用一个 Food 类来表示苦味食物。该类将包括名称和类别属性。
class Food
{
public string Name { get; set; }
public string Category { get; set; }
public Food(string name, string category)
{
this.Name = name;
this.Category = category;
}
}
现在我们可以创建一些 Food 实例:
var coffee = new Food("Coffee", "Beverage");
var chocolate = new Food("Chocolate", "Dessert");
var kale = new Food("Kale", "Vegetable");
var grapefruit = new Food("Grapefruit", "Fruit");
var beer = new Food("Beer", "Alcohol");
接下来,我们将这些食物放在一个列表中:
var foods = new List<Food> { coffee, chocolate, kale, grapefruit, beer };
我们将使用 switch 语句根据类别过滤食物:
switch (category)
{
case "Beverage":
return foods.Where(food => food.Category == "Beverage");
case "Dessert":
return foods.Where(food => food.Category == "Dessert");
case "Vegetable":
return foods.Where(food => food.Category == "Vegetable");
case "Fruit":
return foods.Where(food => food.Category == "Fruit");
case "Alcohol":
return foods.Where(food => food.Category == "Alcohol");
default:
return null;
}
最后,我们使用 foreach 循环将筛选出的食物输出到控制台:
foreach (var food in filteredFoods)
{
Console.WriteLine($"{food.Name} ({food.Category})");
}
本示例介绍了如何使用 C# 编写一个苦味食物程序。我们使用一个 Food 类来表示食物,并将它们放在一个列表中。我们使用 switch 语句来选择特定类别的食物,并用 foreach 循环将它们输出到控制台。这个程序可以帮助你了解 C# 中的类、列表、switch 和循环语句的使用。
代码片段如下:
```csharp
class Food
{
public string Name { get; set; }
public string Category { get; set; }
public Food(string name, string category)
{
this.Name = name;
this.Category = category;
}
}
var coffee = new Food("Coffee", "Beverage");
var chocolate = new Food("Chocolate", "Dessert");
var kale = new Food("Kale", "Vegetable");
var grapefruit = new Food("Grapefruit", "Fruit");
var beer = new Food("Beer", "Alcohol");
var foods = new List<Food> { coffee, chocolate, kale, grapefruit, beer };
switch (category)
{
case "Beverage":
return foods.Where(food => food.Category == "Beverage");
case "Dessert":
return foods.Where(food => food.Category == "Dessert");
case "Vegetable":
return foods.Where(food => food.Category == "Vegetable");
case "Fruit":
return foods.Where(food => food.Category == "Fruit");
case "Alcohol":
return foods.Where(food => food.Category == "Alcohol");
default:
return null;
}
foreach (var food in filteredFoods)
{
Console.WriteLine($"{food.Name} ({food.Category})");
}