누군가가 다음 캐스트가 작동하지 않는 이유와 문제의 해결책을 설명해 주시겠습니까?InvalidCastException : 객체에 대한 목록을 캐스팅 할 수 없습니다.
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>
에 캐스팅하고 싶은 :
GroupedResult
있습니다. 나는 다음과 같은 다른 방법을 시도했다.
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]'.
클래스 '의''GroupedResult <문자열 object> 아닌 <베이컨 문자열>이 있으므로'GropuedResult 불변이다. – Lee