2014-07-24 2 views
0

기본 클래스가 동일한 인터페이스를 구현하는 일반 목록을 만들고 싶은 일반 클래스가 있습니다. 그러나 모든 인터페이스가 특정 인터페이스를 구현하는 것은 아닙니다.C#에서 일반 개체의 일반 목록 만들기

예제는 문제를 설명하는 것보다 쉽습니다.

internal interface ISomething 
{ 

} 

internal class ThisThing : ISomething 
{ 
} 

internal class ThatThing : ISomething 
{ 

} 

internal class SomethingElse 
{ 

} 

internal class GenericThing<T> 
{ 

} 

internal class DoThings 
{ 
    void Main() 
    { 
     var thing1 = new GenericThing<ThisThing>(); 
     var thing2 = new GenericThing<ThatThing>(); 

     var thing3 = new GenericThing<SomethingElse>(); 

     **var thingList = new List<GenericThing<ISomething>>() {thing1, thing2};** 
    } 

은} 나는 thingList를 만들 수 없습니다입니다. 동일한 인터페이스를 구현하는 두 가지를 generic 컬렉션으로 형변환하는 한편, GenericThing 클래스는 인터페이스에 제약되지 않도록 유지할 수 있습니까?

+7

그래서 정확하게 당신의 질문은 무엇입니까? –

+0

'thing'을'List'에 추가하고 싶습니까? – barrick

+3

'GenericThing'은 일반 인자에 대해 공변 적이 지 않으므로 작동하지 않습니다. – Servy

답변

4

당신이 covariant interface 사용하는 경우이 가능하다 : TIGenericThing<T>에서 출력으로 사용하는 경우이 결코 입력으로 만 가능하다는 것을

internal interface IGenericThing<out T> 
{ 
} 

internal class GenericThing<T> : IGenericThing<T> 
{ 
} 

void Main() 
{ 
    var thing1 = new GenericThing<ThisThing>(); 
    var thing2 = new GenericThing<ThatThing>(); 

    var thing3 = new GenericThing<SomethingElse>(); 

    var thingList = new List<IGenericThing<ISomething>>() {thing1, thing2}; 
} 

참고! (필자의 예에서와 같이 사용하지 않는 것이 허용되지만, 분명히 쓸모가 없다.)

+0

그게 내가 찾고 있던거야. 감사. – JNappi