gpt4 book ai didi

c# - 当 LINQ 查询 ToList() 转换为特定的 List 子类时无法转换对象

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

我收到一个运行时异常并且无法弄清楚原因

Unable to cast object of type 'System.Collections.Generic.List`1[Foo.ElementNameViewModel]' to type 'Foo.ElementNameList'.

我上的课是

ElementNameList - 特定类型的列表

namespace Foo
{
public class ElementNameList : List<ElementNameViewModel> {}
}

ElementNameViewModel - 列表中的项目

namespace Foo
{
public class ElementNameViewModel
{
public string Symbol { get; set; }
public string Name { get; set; }
}
}

异常发生在 Controller 中

var elements = (ElementNameList) db.Elements
.Select(c => new ElementNameViewModel
{
Symbol = c.Symbol,
Name = c.Name
})
.OrderBy(e => e.Symbol)
.ToList();

如果未完成子类化列表,我不确定应该如何重构元素列表。

最佳答案

ToList()返回一个真实的 System.Collections.Generic.List例如,不是你的 ElementNameList .

你可以投ElementNameListIList<ElementNameViewModel>List<ElementNameViewModel> ,但不是相反。

原因是因为你的ElementNameList可能具有 List<ElementNameViewModel> 的属性没有。如果您在转换后尝试访问该属性,会发生什么情况?

public class ElementNameList : List<ElementNameViewModel> {
public int X { get; set; }
}

var list = new List<ElementNameViewModel>();
ElementNameList elementList = (ElementNameList) list;
int x = elementList.X; // List<ElementNameViewModel> doesn't have 'X' property, what would happen here?

关于c# - 当 LINQ 查询 ToList() 转换为特定的 List<T> 子类时无法转换对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634620/

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