如何创建一个包含类的类?

时间:2017-07-27 09:49:44

标签: c# class reference

我想制作一个程序,在单独的页面上列出食谱,成分和成分。

我正在考虑创建课程&#34; Ingredient&#34;和&#34;食谱&#34;。 &#34;食谱&#34; class将具有名称和描述属性以及Dictionary<Ingredient, int>属性。我正在考虑用#34; ingredient&#34;填写字典。课程及其所需的金额,例如,让我说我创建了一个&#34; Recipe&#34;把它命名为#34; Pancakes&#34;。我将添加一个名为&#34; Milk&#34;的新Ingredient实例。到数量为100的字典(例如)并为&#34; egg&#34;做同样的事情。等等。

这是解决这种问题的正确方法,因为我想在&#34;成分&#34;上创建参考或链接到成分本身。网页?

3 个答案:

答案 0 :(得分:2)

您所描述的方式将正常运作。但是,您所描述的常见解决方案是装饰器模式。装饰器模式用于创建动态对象。

https://www.youtube.com/watch?v=j40kRwSm4VE

这个例子是使用比萨饼和浇头,但它的概念基本相同。

答案 1 :(得分:0)

这样的事情会起作用:

public enum UnitOfMeasurement
{
    Grams,
    Milliliters
}

public class Ingredient
{
    public UnitOfMeasurement UnitOfMeasurement { get; set; }

    public decimal Unit { get; set; }

    public string Name { get; set; }
}

public class Recipe
{
    public string Description { get; set; }
    public List<Ingredient> Ingredients { get; set; }
    public List<string> RecipeSteps { get; set; }
}

我可能也想为食谱步骤创建一个类或一些更复杂的对象,但这在很大程度上取决于你想用它做什么。

答案 2 :(得分:0)

最近在一次采访中,我被要求做这样的事情,不得不放入一个食谱,然后通过重写ToString()方法将其打印出来。显然可以清理很多,但是总的思路就在那里。

出现以下代码:

using System;

namespace cSHARP
{
    class Program
    {
        static void Main(string[] args)
        {

            Recipe myRecipe = new Recipe();
            Ingredient myIngredient = new Ingredient();
            Ingredient myIngredient2 = new Ingredient();

            myRecipe.Name = "Fish and Chips";

            myIngredient.Name = "Fish";
            myIngredient.Amount = 3;
            myIngredient.AmountType = "pieces";

            myIngredient2.Name = "Chips";
            myIngredient2.Amount = 1;
            myIngredient2.AmountType = "regular serving";

            myRecipe.Ingredients = new Ingredient[2];

            myRecipe.Ingredients[0] = myIngredient;
            myRecipe.Ingredients[1] = myIngredient2;

            Console.WriteLine(myRecipe.ToString());
        }
    }

    public class Recipe
    {
        public string Name { get; set; }
        public Ingredient[] Ingredients { get; set; }

        public override string ToString()
        {
            string retVal = "";

            retVal = retVal + "\n Recipe Name is " + this.Name;
            retVal = retVal + "\n Ingredient one is "
                + this.Ingredients[0].Amount.ToString() + " "
                + this.Ingredients[0].AmountType.ToString() + " of "
                + this.Ingredients[0].Name;
            retVal = retVal + "\n Ingredient two is "
                + this.Ingredients[1].Amount.ToString() + " "
                + this.Ingredients[1].AmountType.ToString() + " of "
                + this.Ingredients[1].Name;


            return (retVal);
        }
    }

    public class Ingredient
    {
        public string Name { get; set; }
        public int Amount { get; set; }
        public string AmountType { get; set; }
    }
}