简体   繁体   English

C#如何在方法中引用对象

[英]C# how to refer to objects inside a method

So i need to create a class called "store" in this class i need to have a method called "start", now in said method i need to create 9 objects from different classes.所以我需要在这个类中创建一个名为“store”的类,我需要一个名为“start”的方法,现在在所述方法中我需要从不同的类创建 9 个对象。 I then need to call on said method in the main program and be able to refer to said created objects after having called the message.然后我需要在主程序中调用所述方法,并能够在调用消息后引用所述创建的对象。

class Store
{
    public void start()
    {
        Pizza vesuvio = new Pizza("Vesuvio", 75, "Tomato", "Cheese", "Ham");
        Pizza vegetarian = new Pizza("Vegetarian", 80, "Tomato", "cheese", "vegetables");
        Pizza contadina = new Pizza("Containda", 75, "Tomato", "cheese", "mushrooms", "olives");

        Costumer victor = new Costumer("Victor", "Hansen");
        Costumer jacob = new Costumer("Jacob", "Pedersen");
        Costumer maghrete = new Costumer("Maghrete", "Ingrid");

        Order victorOrdre = new Order(vesuvio.PizzaPrice, 1.25, vesuvio.PizzaPrice * 1.25);
        Order jacobOrdre = new Order(vegetarian.PizzaPrice, 1.25, vegetarian.PizzaPrice * 1.25);
        Order maghreteOrdre = new Order(contadina.PizzaPrice, 1.25, contadina.PizzaPrice * 1.25);
        return;
    }
}

This is the method i have created but i can't seem to be able to call the method in the main program no matter what i return or what i change the type to.这是我创建的方法,但无论我返回什么或将类型更改为什么,我似乎都无法在主程序中调用该方法。 This is what i've been instructed to do这是我被指示要做的

  1. To test your application you should create a class Store with a method Start.要测试您的应用程序,您应该使用方法 Start 创建一个类 Store。
  2. Call the Start method from the main method in the class Program.从类 Program 中的 main 方法调用 Start 方法。
  3. In the Start method you should:在 Start 方法中,您应该:
  4. Create 3 Pizza objects, 3 Customer objects and 3 Order objects each with a different pizza.创建 3 个 Pizza 对象、3 个 Customer 对象和 3 个 Order 对象,每个对象都有不同的比萨饼。
  5. Print out order information打印订单信息
  6. Using the object reference to each Order object, you should print out the pizza name, the customer name and the total price for each order.使用对每个 Order 对象的对象引用,您应该打印出每个订单的披萨名称、客户名称和总价。
public class Order
{
    // instance fields

    private double _tax;
    private int _priceBeforeTaxes;
    private double _totalPrice;

    //properties

    public double Tax
    {
        get { return _tax; }
        set { _tax = 0.25; }

    }

    public int PriceBeforeTaxes
    {
        get { return _priceBeforeTaxes; }
    }

    public double TotalPrice
    {
        get { return _totalPrice; }
    }

    //constructor
    public Order(int priceBeforeTax, double tax, double totalPrice)
    {
        _priceBeforeTaxes = priceBeforeTax;
        _tax = tax;
        _totalPrice = totalPrice;
    }

    //methods

    public override string ToString()
    {
        string obj = $"order total before taxes is {PriceBeforeTaxes} with taxes of 25% is equal to {TotalPrice} ";
        return obj;
    }

    public double CalculateTotalPrice(int PriceBeforeTaxes, double Tax)
    {
        double CalculatedTotalPrice = PriceBeforeTaxes * Tax;
        return CalculatedTotalPrice;

    }
}

public class Pizza
{

    private string _pizzaName;
    public int _pizzaPrice;
    private string _pizzaToppings1;
    private string _pizzaToppings2;
    private string _pizzaToppings3;
    private string _pizzaToppings4;

    //Properties
    public string PizzaName
    {
        get { return _pizzaName; }
    }

    public int PizzaPrice
    {
        get { return _pizzaPrice; }
    }

    public string PizzaToppings1
    {
        get { return _pizzaToppings1; }
    }

    public string PizzaToppings2
    {
        get { return _pizzaToppings2; }
    }
    public string PizzaToppings3
    {
        get { return _pizzaToppings3; }
    }
    public string PizzaToppings4
    {
        get { return _pizzaToppings4; }
    }

    //constructor
    public Pizza(string pizzaName, int pizzaPrice, string pizzaToppings1, string pizzaToppings2, string pizzaToppings3)
    {
        _pizzaName = pizzaName;
        _pizzaPrice = pizzaPrice;
        _pizzaToppings1 = pizzaToppings1;
        _pizzaToppings2 = pizzaToppings2;
        _pizzaToppings3 = pizzaToppings3;
    }

    public Pizza(string pizzaName, int pizzaPrice, string pizzaToppings1, string pizzaToppings2, string pizzaToppings3, string pizzaToppings4)
    {
        _pizzaName = pizzaName;
        _pizzaPrice = pizzaPrice;
        _pizzaToppings1 = pizzaToppings1;
        _pizzaToppings2 = pizzaToppings2;
        _pizzaToppings3 = pizzaToppings3;
        _pizzaToppings4 = pizzaToppings4;
    }

    //method
    public override string ToString()
    {
        string obj = $"{PizzaName} with {PizzaToppings1}, {PizzaToppings2}, {PizzaToppings3}, {PizzaToppings4} costs {PizzaPrice}kr";
        return obj;
    }


}

public class Costumer
{

    private string _costumerFirstName;
    private int _costumerNumber;
    private string _costumerAddress;
    private string _costumerLastName;

    //properties
    public string CostumerFirstName
    {
        get { return _costumerFirstName; }
        set { _costumerFirstName = value; }
    }
    public string CostumerLastName
    {
        get { return _costumerLastName; }
        set { _costumerLastName = value; }
    }

    public int CostumerNumber
    {
        get { return _costumerNumber; }
        set { _costumerNumber = value; }
    }

    public string CostumerAddress
    {
        get { return _costumerAddress; }
        set { _costumerAddress = value; }
    }

    //constructor
    public Costumer(string CostumerFirstName, string CostumerLastName, int CostumerNumber, string CostumerAddress)
    {
        _costumerFirstName = CostumerFirstName;
        _costumerNumber = CostumerNumber;
        _costumerAddress = CostumerAddress;
        _costumerLastName = CostumerLastName;

        if (CostumerNumber < 100000000 && CostumerNumber > 9999999)
        {

        }
        else
        {
            Console.WriteLine("this is not a valid phone number, valid phone number must be 8 digits. Please try again.");
        }

    }

    //methods
    public override string ToString()
    {
        string obj = $"{CostumerFirstName}, {CostumerLastName}, \n{CostumerNumber}, \n{CostumerAddress}";
        return obj;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Store store = new Store();
        store.start();
    }
}

That is where i'm supposed to call the method and refer to the objects i created in the method.那就是我应该调用该方法并引用我在该方法中创建的对象的地方。

Creating a class is straight forward if you're using visual studio.如果您使用的是 Visual Studio,那么创建一个类是直接的。 This MSDN article (which seems to be exactly what you're looking for) goes more indepth on how to create and use classes.这篇 MSDN 文章(似乎正是您要找的)更深入地介绍了如何创建和使用类。 Have a look at the example section: https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/classes看看示例部分: https : //docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/classes

Below I've gone more in depth on each of your requirements.下面我更深入地介绍了您的每个要求。


  1. To test your application you should create a class Store with a method Start.要测试您的应用程序,您应该使用方法 Start 创建一个类 Store。
namespace PizzaStore
{
    public class Store
    {
        public void Start()
        {
            // Create 3 Pizza objects
            // Create 3 Customer objects
            // Create 3 Order objects each with a different pizza.
        }
    }
}
  1. Call the Start method from the main method in the class Program.从类 Program 中的 main 方法调用 Start 方法。

Find the file called Program.cs , if you are using the new .NET 6 framework then this file will look different.找到名为Program.cs的文件,如果您使用的是新的 .NET 6 框架,则该文件看起来会有所不同。 Otherwise if you're using the .Net Framework 4.x then it should look like a traditional class.否则,如果您使用 .Net Framework 4.x,那么它应该看起来像一个传统类。 See this MSDN documentation for more information: https://docs.microsoft.com/en-gb/dotnet/core/tutorials/top-level-templates有关详细信息,请参阅此 MSDN 文档: https : //docs.microsoft.com/en-gb/dotnet/core/tutorials/top-level-templates

To call the Start() function, you will need to create a new instance of the Store object and then call the function via referencing that instance.要调用Start()函数,您需要创建Store对象的新实例,然后通过引用该实例调用该函数。

Store store = new Store();
store.Start();

If you decide to use this code, you will need to make sure you include a using statement at the top of your file.如果您决定使用此代码,则需要确保在文件顶部包含 using 语句。 You can find more information on namespaces here: https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/namespaces您可以在此处找到有关命名空间的更多信息: https : //docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/namespaces

Namespace:命名空间:

using PizzaStore;

Otherwise you will have to refer to the class including the namespace.否则,您将不得不引用包含命名空间的类。

PizzaStore.Store store = new PizzaStore.Store();
store.Start();
  1. and 4. In the Start method you should: Create 3 Pizza objects, 3 Customer objects and 3 Order objects each with a different pizza.和 4. 在 Start 方法中,您应该: 创建 3 个 Pizza 对象、3 个 Customer 对象和 3 个 Order 对象,每个对象都有不同的比萨饼。

It seems like you've already created the objects.您似乎已经创建了对象。 As far as I can see, what you've done is correct in regards to creating the objects.据我所知,您在创建对象方面所做的工作是正确的。 You can set the variables up in different ways (for example using properties: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties ) but what you've done by initialising the values in the constructor is perfectly fine.您可以以不同的方式设置变量(例如使用属性: https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties )通过在构造函数中初始化值来完成是完全没问题的。

The only improvement I would suggest is to remove the return;我建议的唯一改进是删除return; at the end of the function.在函数的最后。 This serves no purpose and may be confusing.这没有任何意义,并且可能会令人困惑。

  1. and 6. Print out order information: Using the object reference to each Order object, you should print out the pizza name, the customer name and the total price for each order.和 6. 打印订单信息:使用对每个订单对象的对象引用,您应该打印出每个订单的披萨名称、客户名称和总价。

I assume you are using a console project.我假设您正在使用控制台项目。 In which case writing to the console is simple.在这种情况下,写入控制台很简单。

To write a single line you can use:要编写一行,您可以使用:

Console.WriteLine("Hello, World!");

To write something without creating a new line you can use:要在不创建新行的情况下编写内容,您可以使用:

Console.Write("Hello, World!");

In order to reference each object you've made, it's as simple as using the declared variable name you created for them, for example:为了引用您创建的每个对象,就像使用您为它们创建的声明变量名称一样简单,例如:

Console.WriteLine(vesuvio.PizzaName);

This final requirement of your task will need you to modify the code you currently have.您的任务的最终要求将需要您修改当前拥有的代码。 When you're creating an order, you will need to enter data which will help identify the order.创建订单时,您需要输入有助于识别订单的数据。

Right now, you have the price of the pizza and what I am assuming is the tax rate and the final total price.现在,你有披萨的价格,我假设的是税率和最终总价。

Unfortunately, this does not help us identify the order because we can't figure out what type of pizza was ordered and who ordered the pizza.不幸的是,这并不能帮助我们识别订单,因为我们无法确定订购的是哪种类型的比萨饼以及谁订购了比萨饼。 Therefore, you will need to add these 2 key parts of the data within the order.因此,您需要在订单中添加这两个关键数据部分。

I recommend adding a property in the Order class for the objects you created called:我建议在Order类中为您创建的对象添加一个属性,称为:

  • Pizza比萨
  • Customer顾客

You can do this in the same way you created the string and numbers to pass in the constructor.您可以按照创建要传入构造函数的字符串和数字的相同方式执行此操作。 But make sure this is stored in the class and not just passed into the constructor.但请确保它存储在类中,而不仅仅是传递给构造函数。

For example your Customer class would look something like this:例如,您的 Customer 类将如下所示:

public class Custumer
{
    public Custumer(string name, string surname)
    {
        CustomerName = name;
        CustomerSurname = surname;
    }

    public string CustomerName { get; set; }
    public string CustomerSurname { get; set; }

}

And your Order class would look something like this:您的 Order 类将如下所示:

public class Order
{
    public Order(double price, Customer customer)
    {
        OrderPrice = price;
        OrderCustomer = customer;
    }

    public double OrderPrice { get; set; }
    public Customer OrderCustomer { get; set; }
}

You can reference the order customer by doing something like this:您可以通过执行以下操作来引用订单客户:

victorOrdre.OrderCustomer.CustomerName;

It seems like you've updated your answer with your code.您似乎已使用代码更新了答案。 That's very helpful in identifying how to help you.这对于确定如何帮助您非常有帮助。 In regards to your update, it's clear you have a good understanding of classes and properties.关于您的更新,很明显您对类和属性有很好的了解。

For the Pizza class, I would recommend you use a list with an array of pizza ingredients instead.对于 Pizza 类,我建议您使用包含一系列披萨配料的列表。 This way you don't need to create a new variable for each topping.这样您就不需要为每个浇头创建一个新变量。

public class Pizza
{
    public Pizza(string name, double price, params string[] args)
    {
        PizzaName = name;
        PizzaPrice = price;
        PizzaIngredients = new List<string>();

        foreach (var item in args)
        {
            PizzaIngredients.Add(item);
        }
    }

    public string PizzaName { get; set; }
    public double PizzaPrice { get; set; }
    public List<string> PizzaIngredients { get; set; }
}

It sounds to me, based on the instructions that you've posted, that all you need for full-marks is this:根据您发布的说明,在我看来,获得满分所需的只是:

class Program
{
    static void Main(string[] args)
    {
        Store store = new Store();
        store.Start();
    }
}

public class Store
{
    public void Start()
    {
        Order[] orders = new []
        {
            new Order(new Customer("Victor Hansen"), new Pizza("Vesuvio", 75m)),
            new Order(new Customer("Jacob Pedersen"), new Pizza("Vegetarian", 80m)),
            new Order(new Customer("Maghrete Ingrid"), new Pizza("Containda", 75m)),
        };

        foreach (Order order in orders)
        {
            Console.WriteLine($"{order.Customer.Name} has ordered {order.Pizza.Name} costing {order.Pizza.Price}.");
        }
    }
}

public class Order
{
    public Customer Customer { get; private set; }
    public Pizza Pizza { get; private set; }

    public Order(Customer customer, Pizza pizza)
    {
        this.Customer = customer;
        this.Pizza = pizza;
    }
}

public class Pizza
{
    public string Name { get; private set; }
    public decimal Price { get; private set; }

    public Pizza(string name, decimal price)
    {
        this.Name = name;
        this.Price = price;
    }
}

public class Customer
{
    public string Name { get; private set; }

    public Customer(string name)
    {
        this.Name = name;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM