【问题标题】:what do these custom return types do in this example of c#?在这个 c# 示例中,这些自定义返回类型有什么作用?
【发布时间】:2021-02-08 01:02:09
【问题描述】:

我知道具有返回类型的函数会将函数的值返回给该函数的调用者。 但是,我无法在实践中解释它。

例如:

public class InMemoryRestaurantData : IRestaurantData
{
    readonly List<Restaurant> restaurants;

    public InMemoryRestaurantData()
    {
        restaurants = new List<Restaurant>()
        {
            new Restaurant { Id = 1, Name = "Scott's Pizza", Location="Maryland", Cuisine=CuisineType.Italian},
            new Restaurant { Id = 2, Name = "Cinnamon Club", Location="London", Cuisine=CuisineType.Italian},
            new Restaurant { Id = 3, Name = "La Costa", Location = "California", Cuisine=CuisineType.Mexican}
        };
    }

    public Restaurant GetById(int id)
    {
        return restaurants.SingleOrDefault(r => r.Id == id);
    }

    public Restaurant Add(Restaurant newRestaurant)
    {
        restaurants.Add(newRestaurant);
        newRestaurant.Id = restaurants.Max(r => r.Id) + 1;
        return newRestaurant;
    }

在此示例中,我不清楚调用 GetById 和 Add 方法返回类型的作用。 如果有人向我描述它,我将不胜感激。

【问题讨论】:

  • 他们说“我返回的东西的类型是Restaurant”。

标签: c# .net methods


【解决方案1】:

您的描述并不完全正确 - 具有返回类型的函数将 该类型的对象或值返回给调用者。所以它可以作为任务的一部分工作,即

Restaurant x = new Restaurant ();

Restaurant x = GetRestaurantById(1);

Restaurant x;
x = GetRestaurantById(1);

所以 GetById 返回一个 Restaurant 对象。你能看到那里的任何 Restaurant 对象吗?

即使没有 Restaurant 类定义,您也可以从 InMemoryRestaurantData 中的列表中推断出关于 Restaurant 对象的一些信息 - 正在创建 Restaurant 对象列表,每个对象都有 Id、Name、Location 和 Cuisine。

因此,您可以预期,如果您声明一个新的 Restaurant 变量并使用 Restaurant.GetById(1),该餐厅对象将是 Scott's Pizza,而 .Location 将包含 Maryland,依此类推...

【讨论】:

  • 你的描述让我明白了。谢谢你。
【解决方案2】:

当您调用 GetById 并传递一个 id 值时,您期望返回一个具有相同 id 的 Restaurant 类型的对象。

当您使用新餐厅调用 Add 时,如果添加操作成功,您将返回相同的对象。

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 2012-03-06
    相关资源
    最近更新 更多