簡體   English   中英

無法隱式轉換類型,存在顯式轉換(您是否缺少強制轉換?)

[英]Cannot implicitly convert type, explicit conversion exists (are you missing a cast?)

我有一個錯誤:

(無法將類型“shenoy webapi.Models.PartIndex”隱式轉換為“System.Collections.Generic.IEnumerable”。存在顯式轉換(您是否缺少演員表?) shenoywebapi D:\\shenoystudio\\shenoywebapi\\Controllers\\RateController.cs 69積極的)

[Route("api/Rate/getproductrate")]
public IEnumerable<Rate> GetProductRate()
{
    var list = new List<Rate>();
    var dsRate = SqlHelper.ExecuteDataset(AppDatabaseConnection, CommandType.StoredProcedure, 0, "GetProductRates");

    if (dsRate.Tables[0].Rows.Count > 0)
    {
        foreach (DataRow row in dsRate.Tables[0].Rows)
        {
            list.Add(new Rate
            {
                Id = Convert.ToInt64(row[0]),
                SerialNumber = row[1].ToString(),
                ProductName = row[2].ToString(),
                Unit = row[3].ToString(),
                PartIndex = new PartIndex { Series = row[4].ToString() },
            });
        }
    }
    return list;
}

這是我的模型:

namespace shenoywebapi.Models
{
    public class Rate
    {
        public long Id { get; set; }
        public DateTime wefDate { get; set; }
        public string SerialNumber { get; set; }
        public string ProductName { get; set; }
        public string Unit { get; set; }
        public long Rates { get; set; }
        public IEnumerable<PartIndex> PartIndex { get; set; }
    }
}

嚴重性代碼描述項目文件行抑制狀態錯誤 CS0266 無法將類型“shenoywebapi.Models.PartIndex”隱式轉換為“System.Collections.Generic.IEnumerable”。 存在顯式轉換(您是否缺少演員表?) shenoywebapi D:\\shenoystudio\\shenoywebapi\\Controllers\\RateController.cs 69 Active

在您的 Rate 類中,您有一個屬性定義為:

public IEnumerable<PartIndex> PartIndex { get; set; }  

在您的函數中,您試圖將其分配為:

PartIndex = new PartIndex { Series = row[4].ToString() } 

所以你試圖分配一個對象而不是一個 IEnumerable。 嘗試將分配包裝在new List() {...}以修復它。
該錯誤還非常清楚地告訴您:

無法將類型“PartIndex”隱式轉換為“System.Collections.Generic.IEnumerable”

這意味着它不能自動將單個對象轉換為僅包含該對象的 IEnumerable。 你必須手動完成。

是這條線

PartIndex = new PartIndex { Series = row[4].ToString() }

在你的模型PartIndex必須是IEnumerable<PartIndex>它必須是

PartIndex = new List<PartIndex>() { new PartIndex() {Series = row[4].ToString()} }

首先IEnumerable<PartIndex>可以通過List<PartIndex>創建 所以創建 IEnumerable 就像

PartIndex = new List<PartIndex>();

並插入您的元素,如:

PartIndex = new List<PartIndex>() { new PartIndex() {Series = row[4].ToString()} }

最后你可以看看,它談論 IEnumrable 和 List。 IEnumerable 與列表 - 使用什么? 它們是如何工作的?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM