문제

다음 코드를 어떻게 작동하게 만들 수 있나요?저는 C# 제네릭을 잘 이해하지 못하는 것 같습니다.아마도 누군가가 나에게 올바른 방향을 알려줄 수 있을 것입니다.

    public abstract class A
    {
    }

    public class B : A
    {
    }

    public class C : A
    {
    }

    public static List<C> GetCList()
    {
        return new List<C>();
    }

    static void Main(string[] args)
    {
        List<A> listA = new List<A>();

        listA.Add(new B());
        listA.Add(new C());

        // Compiler cannot implicitly convert
        List<A> listB = new List<B>();

        // Compiler cannot implicitly convert
        List<A> listC = GetCList();

        // However, copying each element is fine
        // It has something to do with generics (I think)
        List<B> listD = new List<B>();
        foreach (B b in listD)
        {
            listB.Add(b);
        }
    }

아마도 간단한 대답일 것이다.

업데이트:첫째, 이는 C# 3.0에서는 불가능하지만 C# 4.0에서는 가능합니다.

4.0까지의 해결 방법인 C# 3.0에서 실행하려면 다음을 사용하세요.

        // Compiler is happy
        List<A> listB = new List<B>().OfType<A>().ToList();

        // Compiler is happy
        List<A> listC = GetCList().OfType<A>().ToList();
도움이 되었습니까?

해결책

당신은 항상 이것을 할 수 있습니다

List<A> testme = new List<B>().OfType<A>().ToList();

"Bojan Resnik"가 지적했듯이, 당신도 할 수도 있습니다 ...

List<A> testme = new List<B>().Cast<A>().ToList();

주목할만한 차이점은 그 캐스트입니다u003CT> 하나 이상의 유형이 일치하지 않으면 () 실패합니다. 유형의 곳u003CT> ()는 ienumerable을 반환합니다u003CT> 전환 가능한 물체 만 포함합니다

다른 팁

이것이 작동하지 않는 이유는 안전하다고 판단할 수 없기 때문입니다.당신이 가지고 있다고 가정

List<Giraffe> giraffes = new List<Giraffe>();
List<Animal> animals = giraffes; // suppose this were legal.
// animals is now a reference to a list of giraffes, 
// but the type system doesn't know that.
// You can put a turtle into a list of animals...
animals.Add(new Turtle());  

그리고 방금 기린 목록에 거북이를 넣었더니 유형 시스템 무결성이 위반되었습니다.그렇기 때문에 이것이 불법입니다.

여기서 핵심은 "동물"과 "기린"이 ​​동일한 개체를 참조하고 해당 개체가 기린 목록이라는 것입니다.그러나 기린의 목록은 동물의 목록만큼 많은 것을 할 수 없습니다.특히 거북이를 포함할 수 없습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top