0

我最近开始学习 C# 并创建了一个面包店项目,人们可以在其中购买面包或糕点。

我的项目工作得很好,但其中一个要求是使用{ get; set }和构造函数。

这是我的 bread.cs 文件:

using System;
using System.Collections.Generic;

namespace Bakery.Models
{
    public class Bread
    { 
        // public Bread(int aNumofBread) 
        // {
        //     int numOfBread = aNumofBread;
        // }
 
        public int CalcBread(int numOfBread) 
        {
            int priceOfLoaf = 5;

            if (numOfBread % 3 == 0) 
            {
                return (numOfBread * priceOfLoaf) - ((numOfBread/3) * priceOfLoaf);     
            } 
            else if (numOfBread % 3 == 1)
            {
                return (numOfBread * priceOfLoaf) - ((numOfBread-1)/3 * priceOfLoaf);
            } 
            else if (numOfBread % 3 == 2)  
            {
                return (numOfBread * priceOfLoaf) - ((numOfBread-2)/3 *priceOfLoaf);
            } 
            else 
                return numOfBread * priceOfLoaf;
        }
    }
};

如您所见,我的班级中没有构造函数。

这是我的 program.cs 的样子:

using System;
using System.Collections.Generic;

namespace Bakery.Models
{
    public class Program
    {
        public static void Main()
        {
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.BackgroundColor = ConsoleColor.Black;

            string bakeryAscii = @"
                          ....
                      .'      `.
                    .' .-'``-._ `.
                    |  / -    - ` |
                    / |'<o>  <o> | \
                    (|    '`    |) 
                      \  -==-  /   
                       `.____.'    
                        |    |     
                  _ _.'`-.__.-'`._/_
                .'| |`-.  /\  .-'| |`.
              _.'   \ \  `'  `'  / /   `._
            { `.    | `-.____.-' |    .' }
            /`. `./ /   __  __   \ \.' .'\
            /   `.| |   /  \/  \   | |.'   \
          (    (  \ \  \      /  / /  )    )
            `.   \  Y|   `.  .'   |Y  /   .'
              \   \ ||_ _ _\/_ _ _|| /   /
              `.  \|'            `|/  .'
        _______/  _ >--------------< _  \______.##._
              ((((_(                )_))))   .##. |
            / ```` `--------------' ''''\   |  | |
            ( Welcome to Bakery! \  |  |-'
            )                             ) `--'
            (          _        _.---.__.-'
            `-.___.--' `------'

        ";
        Console.ForegroundColor = ConsoleColor.DarkBlue;
        Console.WriteLine(bakeryAscii);
        Console.ForegroundColor = ConsoleColor.Gray;
        Console.WriteLine("Please [y] to place your order, [m] to view the menu and [n] to exit");

        string  continueAnswer = Console.ReadLine().ToLower();

        if (continueAnswer == "y")  
        {
            Console.WriteLine("How many loaves of bread would you like to purchase today?");
            string stringNumOfBread = Console.ReadLine(); 

            int numOfBread = 0;
            bool checkBreadInput = Int32.TryParse(stringNumOfBread, out numOfBread);

            if (checkBreadInput == true) 
            {
                if (numOfBread >= 0 ) 
                {
                    Bread bread = new Bread();
                    int breadPrice = bread.CalcBread(numOfBread);

                    Console.WriteLine("You have bought " + numOfBread + " loaves  of bread for: $" + breadPrice);
                    Console.WriteLine("Would you like to buy some Pastry's today? [y] or [n]");

                    string pastryAnswer = Console.ReadLine().ToLower();

                    if (pastryAnswer == "y") 
                    {
                        Console.WriteLine("Please enter the number of pastry's you would like to buy:");
 
                        string stringNumOfPastry = Console.ReadLine(); 
                        int numOfPastry = 0;

                        bool checkPastryInput = Int32.TryParse(stringNumOfPastry,   out numOfPastry);

                        if (checkPastryInput == true) 
                        {
                            if (numOfPastry >= 0) 
                            {
                                Pastry pastry = new Pastry();
                                int pastryPrice = pastry.CalcPastry(numOfPastry);

                                Console.WriteLine("You have bought " + numOfPastry + " pastry's");
                                Console.BackgroundColor = ConsoleColor.Black;
                                Console.ForegroundColor = ConsoleColor.Green;

                                int total = breadPrice + pastryPrice;
                                Console.WriteLine("Your total bill is $" + total);

                                Console.ForegroundColor = ConsoleColor.Gray;
                                Console.WriteLine("Goodbye");
                            } 
                            else 
                                ErrorNegativeNumber(); 
                        } 
                        else 
                            Error();
                    } 
                    else if (pastryAnswer == "n") 
                    {
                        Console.WriteLine("Thank you for coming in, your total bill is $" + breadPrice);
                        Console.WriteLine("Goodbye");
                    } 
                    else 
                        Error();
                } 
                else 
                {  
                     ErrorNegativeNumber();      
                } 
            } 
            else 
                Error();
        } 
        else if (continueAnswer == "m") 
        {
            Menu();
        } 
        else if (continueAnswer == "n") 
        {
            Console.WriteLine("Goodbye");
        } 
        else 
        {
            Error();
        }
    }

    public static void Menu() 
    {
        Console.WriteLine("--------------------------------");
        Console.ForegroundColor = ConsoleColor.Yellow;

        string menu = @"Fresh Bread: $5 each (loaf)
        Delicious Pastry: $2 each

        ** Special of the week **
        Bread: Buy 2, get 1 free!
        Pastry: 3 for $5!";

        Console.WriteLine(menu);
        Console.WriteLine("--------------------------------");
        Console.WriteLine("Press enter to continue");

        string menuAnswer = Console.ReadLine();

        Main();
    }

    public static void Error()  
    {
          Console.ForegroundColor = ConsoleColor.Red;
          Console.WriteLine("Error, Invalid Input");
          Console.WriteLine("Press Enter to Restart");
          Console.ReadLine();

          Main();
    }

    public static void ErrorNegativeNumber() 
    {
          Console.ForegroundColor = ConsoleColor.Red;
          Console.WriteLine("Error, Invalid Input. Negative Input detected.  You owe us bread!");
          Console.WriteLine("Press Enter to Restart");
          Console.ReadLine();

          Main();
    }
}

非常感谢您的帮助,我知道我可以重构我的 program.cs 以使其更加 DRY.. 但现在我只专注于使用自动实现的属性。

我对此感到非常困惑..我希望能得到一些帮助,谢谢。

4

2 回答 2

3

这是Bread具有构造函数方法和一个属性的类,PricePerLoaf. 构造函数接受一个参数,面包价格,并将其设置为PricePerLoaf对象实例化时的属性。该属性设置为可从类外部读取,但只能从类内部设置/写入,这有助于保护价格在Bread类创建后不被外部设置。

将值传递给构造函数是没有意义的,numOfBread因为每次计算都会改变这个值,因为这个原因numOfBread仍然作为CalcBread方法的参数。但是,CalcBread面包价格具有硬编码值。面包价格 ,PricePerLoaf添加为构造函数参数更有意义,因为它可能会根据面包类型/质量/等而改变。

public class Bread
{
        
    public Bread(int loafPrice)
    {
        // let's ensure a new bread object cannot be created with a price of $0 or less
        // we will throw an exception if the object is initialized with an invalid loaf price
        if(loafPrice <= 0) throw new ArgumentOutOfRangeException(nameof(loafPrice));

        // here we set the PricePerLoaf property from the received constructor argument value
        PricePerLoaf = loafPrice;
    }

    // we create a property for the loaf price; the property can be read outside of this class
    // but can only be set by this class
    public int PricePerLoaf { get; private set; }

    public int CalcBread(int numOfBread)
    {
        // when we calculate the price we use our PricePerLoaf property and no longer use the local 
        // variable 'priceOfLoaf' that was hard coded here, this allows the price to change and different
        // Bread objects with different prices could be implemented (see usage example below)
        if (numOfBread % 3 == 0)
        {
            return (numOfBread * PricePerLoaf) - ((numOfBread / 3) * PricePerLoaf);
        }
        else if (numOfBread % 3 == 1)
        {
            return (numOfBread * PricePerLoaf) - ((numOfBread - 1) / 3 * PricePerLoaf);
        }
        else if (numOfBread % 3 == 2)
        {
            return (numOfBread * PricePerLoaf) - ((numOfBread - 2) / 3 * PricePerLoaf);
        }
        else
        {
            return numOfBread * PricePerLoaf;
        }
    }
}

如何使用新的 Bread 类...

int numOfBread = 10;
Bread cheapBread = new Bread(3);
int cheapBreadPrice = cheapBread.CalcBread(numOfBread);

Bread freshBread = new Bread(5);
int freshBreadPrice = freshBread.CalcBread(numOfBread);

Bread gourmetBread = new Bread(8);
int gourmetBreadPrice = gourmetBread.CalcBread(numOfBread);

Console.WriteLine($"Cheap Bread Price = ${cheapBreadPrice}");
Console.WriteLine($"Fresh Bread Price = ${freshBreadPrice}");
Console.WriteLine($"Gourmet Bread Price = ${gourmetBreadPrice}");

输出将是...

Cheap Bread Price = $21
Fresh Bread Price = $35
Gourmet Bread Price = $56
于 2021-04-30T00:36:52.660 回答
0

感谢您的信息。这是我想出的解决方案:)。


using System;
using System.Collections.Generic;

namespace Bakery.Models
{
    public class Bread
    { 
      
      public int PricePerLoaf { get; private set; }
      public int BreadPrice { get;set; }
      public Bread()
      {
        PricePerLoaf = 5;
        BreadPrice = 0;
      }
       public void CalcBread(int numOfBread) {
          if(numOfBread % 3 == 0) 
          {
            BreadPrice = (numOfBread * PricePerLoaf) - ((numOfBread/3) * PricePerLoaf);     
          } else if(numOfBread % 3 == 1) 
          {
            BreadPrice = (numOfBread * PricePerLoaf) - ((numOfBread-1)/3 * PricePerLoaf);
          } else if (numOfBread % 3 == 2) 
          {
            BreadPrice = (numOfBread * PricePerLoaf) - ((numOfBread-2)/3 *PricePerLoaf);
          } else BreadPrice = numOfBread * PricePerLoaf;
     }
         
    }
}

让我知道你的想法!

https://github.com/FaisalRana/CSharp.Bakery

于 2021-04-30T10:00:06.600 回答