기본 클래스가 동일한 인터페이스를 구현하는 일반 목록을 만들고 싶은 일반 클래스가 있습니다. 그러나 모든 인터페이스가 특정 인터페이스를 구현하는 것은 아닙니다.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 클래스는 인터페이스에 제약되지 않도록 유지할 수 있습니까?
그래서 정확하게 당신의 질문은 무엇입니까? –
'thing'을'List'에 추가하고 싶습니까? – barrick
'GenericThing'은 일반 인자에 대해 공변 적이 지 않으므로 작동하지 않습니다. – Servy