有人请向我解释为什么下面的演员无法正常工作并解决问题。InvalidCastException:无法将泛型列表转换为对象
我有一个GroupedResult
:
public class GroupedResult<TKey, TElement>
{
public TKey Key { get; set; }
private readonly IEnumerable<TElement> source;
public GroupedResult(TKey key, IEnumerable<TElement> source)
{
this.source = source;
this.Key = key;
}
}
public class Bacon
{
}
我想投的List<string, Bacon>
到List<string, object>
。我尝试了以下和其他方法。
var list = new List<GroupedResult<string, Bacon>>
{
new GroupedResult<string, Bacon>("1", new List<Bacon>()),
new GroupedResult<string, Bacon>("2", new List<Bacon>())
};
var result = list.Cast<GroupedResult<string, object>>().ToList();
但我一直得到以下错误:
InvalidCastException: Unable to cast object of type 'GroupedResult
2[System.String,UserQuery+Bacon]' to type 'GroupedResult
2[System.String,System.Object]'.
类是不变的,从而一个'GropuedResult <串,培根>'不是'GroupedResult <串,对象>'。 – Lee