2016-07-07 7 views
1

누군가가 다음 캐스트가 작동하지 않는 이유와 문제의 해결책을 설명해 주시겠습니까?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]'.

+4

클래스 '의''GroupedResult <문자열 object> 아닌 <베이컨 문자열>이 있으므로'GropuedResult 불변이다. – Lee

답변

1

작동하려면 클래스 유형 대신 인터페이스를 사용해야합니다.

public interface IGroupResult<TKey, out TElement> 
{ 
    TKey Key { get; set; } 
} 

public class GroupedResult<TKey, TElement> : IGroupResult<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 
{ 

} 

그럼 당신은 공동 분산은 인터페이스와 대표가 아닌 클래스에서 허용되기 때문이다

IGroupResult<string, Bacon> g = new GroupedResult<string, Bacon>("1", new List<Bacon>()); 

var result = (IGroupResult<string, object>)g; 

뭔가를 할 수 있습니다. 유형이 인터페이스 (메소드 리턴 유형 및 읽기 전용 특성)에서만 나오는 경우 유형을 공동 변형으로 표시해야합니다.

generics로 작업 할 때 object으로 무언가를 캐스팅해야하는 이유는 스스로에게 물어보아야하지만. 제네릭의 핵심은 object 유형을 캐치 (catch)로 사용하지 않아도되므로 다시 생각해 볼 수있는 디자인상의 결함을 나타낼 수 있습니다.

0

GroupedResult < 문자열로 시작하는 더 나은 것, 개체> 다음이

new GroupedResult<string, object>("2", new List<Bacon>()) 
0

왜 때로 믿을 할 수를 0 GroupedResult<string, Bacon> 대신 GroupedResult<string, object>을 사용하고 계십니까? 다음과 같이하십시오 :

var list = new List<GroupedResult<string, object>> 
    { 
     new GroupedResult<string, object>("1", new List<Bacon>()), 
     new GroupedResult<string, object>("2", new List<Bacon>()) 
    }; 
0

GroupedResult 클래스에 Cast 방법을 사용할 수 있으며이를 사용하여 전송을 수행 할 수 있습니다.

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 GroupedResult<TKey, object> Cast() 
    { 
     return new GroupedResult<TKey, object>(Key, source.Cast<object>()); 
    } 
} 

public class Bacon 
{ 
} 

static void Main(string[] args) 
{ 

    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(); 
    List<GroupedResult<string,object>> result = list.Select(B => B.Cast()).ToList(); 
}