gpt4 book ai didi

c# - 无法隐式转换类型 System.Collections.Generic.List

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:17 26 4
gpt4 key购买 nike

Exception: Cannot implicitly convert type 'System.Collections.Generic.List<ModelClass>' to 'System.Collections.Generic.List<ModelClass>'

我想不通我犯了什么错误。这是我所遵循的结构:-

namespace XMailerData.DAL
{
public class Data : IData, IDisposable
{
XmailerEntities context = new XmailerEntities();
public List<PageContentModel> GetPageContent()
{
List<PageContentModel> lPageContent = (from pc in context.T_PageContent
select new PageContentModel
{
contentId = pc.ContentId,
description = pc.Description
}).AsEnumerable().ToList();
return lPageContent;
}
}
}

在上面的类(class)中,我试图返回一个 List,其中包含从 linq 表达式生成的结果并且 PageContentModel 在相同的命名空间中定义,但具有不同的类名。

namespace XMailerData.CompositeModel
{
public class PageContentModel
{
public int pageId { get; set; }
public int contentId { get; set; }
public string description { get; set; }
}
}

现在,在我的另一个名为 Classes 的类库中,我尝试调用下面提到的函数

namespace Classes.Helper
{
public class DAL
{
public static List<PageContentModel> FetchPageContent()
{
IData iData;
List<PageContentModel> lPageContent = new List<PageContentModel>();
lPageContent = iData.GetPageContent(); // Here i'm getting an error
return lPageContent;
}
}
}

在这里,我试图将 iData.GetPageContent() 的结果绑定(bind)到另一个类中定义的另一个列表,但我没有这样做。

namespace Classes.CompositeModel
{
public class PageContentModel
{
public int pageId { get; set; }
public int contentId { get; set; }
public string description { get; set; }
}
}

在我所有的尝试中,我无法解决以下错误:-

Exception: Cannot implicitly convert type 'System.Collections.Generic.List<XMailerData.CompositeModel.PageContentModel>' to 'System.Collections.Generic.List<Classes.CompositeModel.PageContentModel>'

有人可以帮助我解决这个问题并承认我犯了什么错误,因为我犯了这样的错误。

结论:

感谢您的见解,它真的很有帮助。现在我修改了我的代码,它现在可以正常工作了。这是我现在所做的。

namespace Classes.Helper
{
public class DAL
{
public static List<PageContent> FetchPageContent()
{
IData iData = new Data();
List<PageContent> lPageContent = new List<PageContent>();
lPageContent = iData.GetPageContent()
.Select(pc => new PageContent
{
pageId = pc.pageId,
contentId = pc.contentId,
description = pc.description,
}).ToList();
return lPageContent;
}
}
}

为了避免歧义,我已将属性类从 PageContentModel 重命名为 PageContent。感谢 Reza AghaeiMonroe ThomasNikita 分享建议。 Reza AghaeiMonroe Thomas 都是可以接受的,但不可能接受两个答案,所以我接受一个答案并赞成休息。

最佳答案

XMailerData.CompositeModel.PageContentModelClasses.CompositeModel.PageContentModel 具有相同的属性,但它们驻留在不同的命名空间中,这使它们成为两个不同的类。因此,Data 类应该引用 Classes.CompositeModel.PageContentModel 而不是 XMailerData.CompositeModel.PageContentModel

关于c# - 无法隐式转换类型 System.Collections.Generic.List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32514767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com