【发布时间】:2021-03-18 04:24:56
【问题描述】:
我正在尝试查看是否可以将菜单对象转换为食物。我将按照我的建议放入界面。
在我的自助餐代码中,在将所有东西添加到菜单对象后调用我的 Food 方法,我的目标是随机选择要吃的食物然后返回信息。
我希望我可以做一些事情,比如在我得到 mo =(Food) Menu[rand.Next(Menu.Count)]; 的地方可以让我轻松做到这一点。
我错了,我可能过于复杂了,因为我要返回 mo 但每次我尝试投射它时,它都不起作用。
也许我可以使用枚举器或其他东西,但这非常令人困惑。我想我对自己想要的东西有正确的想法,但是用语言表达很困难,所以谢谢大家对我的耐心。我希望这能更好地解释它:
我的自助餐课
using System;
using System.Collections.Generic;
namespace IronNinja.Models
{
class Buffet
{
public List<Food> Foods = new List<Food>();
public List<Drink> Dranks = new List<Drink>();
public List<object> Menu = new List<object>();
//constructor
public Buffet()
{
Menu.Add(new Food("Chicken Pizza", 1000, false, true));
Menu.Add(new Food("Buffalo Chicken Pizza", 1000, true, false));
Menu.Add(new Food("Lasagna", 1200, false, true));
Menu.Add(new Food("Garden Salad WSalad dressing", 700, true, false));
Menu.Add(new Food("sour patch kids whole box", 700, false, true));
Menu.Add(new Drink("Rootbeer", 700, false));
Menu.Add(new Drink("Not Your Father's Rootbeer", 900, false));
}
// Add a constructor and Serve method to the Buffet class
public Food Serve()
{
Random rand = new Random();
Food mo = ((Food) Menu[rand.Next(Menu.Count)]);
Console.WriteLine(mo);
return new Food("sour patch kids whole box", 700, false, true);
}
}
}
我的饮料课
using IronNinja.Interfaces;
namespace IronNinja.Models
{
public class Drink : IConsumable
{
public string Name { get; set; }
public int Calories { get; set; }
public bool IsSpicy { get; set; }
public bool IsSweet { get; set; }
// Implement a GetInfo Method
public string GetInfo()
{
return $"{Name} (Drink). Calories: {Calories}. Spicy?: {IsSpicy},
Sweet?: {IsSweet.Equals(true)}";
}
// Add a constructor method
public Drink(string name, int calories, bool spicy)
{
Name = name;
Calories = calories;
IsSpicy = spicy;
IsSweet = true;
}
}
}
我的美食课
using IronNinja.Interfaces;
namespace IronNinja.Models
{
class Food : IConsumable
{
public string Name { get; set; }
public int Calories { get; set; }
public bool IsSpicy { get; set; }
public bool IsSweet { get; set; }
public string GetInfo()
{
return $"{Name} (Food). Calories: {Calories}. Spicy?: {IsSpicy},
Sweet?: {IsSweet}";
}
public Food(string name, int calories, bool spicy, bool sweet)
{
Name = name;
Calories = calories;
IsSpicy = spicy;
IsSweet = sweet;
}
}
}
【问题讨论】:
-
我用如何获得随机食物的样本更新了我的答案。
标签: c# csharpcodeprovider