【问题标题】:You can not implicitly convert "RESTfullApi.Models.Product []" to "RESTfullApi.Models.Product"您不能将“RESTfullApi.Models.Product []”隐式转换为“RESTfullApi.Models.Product”
【发布时间】:2017-05-15 01:57:05
【问题描述】:

我正在尝试学习如何创建 Web Api,但我遇到了一个错误。

我不知道该怎么办,首先我使用它时需要使用后缀M,VS显示错误:

您不能将“RESTfullApi.Models.Product []”隐式转换为 "RESTfullApi.Models.Product"

我试图在互联网上找到答案,但没有解释这个案例。 也许你知道它有什么问题?

这是我练习的教程: https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

ProductsController.cs

using RESTfullApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace RESTfullApi.Controllers
{
    public class ProductsController : ApiController
    {
        Product products = new Product[]
        {
            new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
            new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }
    }
}

Product.cs(模型)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RESTfullApi.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}

【问题讨论】:

  • Product products = new Product[] 你是说你有一个名为products 类型为Product 的变量——产品的单个实例,你给它分配了一个产品数组——类型不匹配。将变量类型更改为Product[]。或者您可以简单地使用var 进行声明,这样可以省去您将来的一些思考(var products = new Product[] {

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

消息是不言自明的。将products 更改为

Product[] products = new Product[]
{
    new Product { Id = 1, Name = "Pizza Margarita", Category = "Pizza", Price = 13.00M },
    new Product { Id = 2, Name = "Pizza Double Cheese", Category = "Pizza", Price = 17.00M }
};

【讨论】:

    猜你喜欢
    • 2017-07-17
    • 2011-12-10
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多