AddRange를 사용하여 서브 클래스 항목을 추가 할 수없는 이유는 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1072581

문제

나는 두 가지 수업이 있습니다 .... 소포와 펀드 파이 ... 그리고 하위 유형의 ienumerable을 슈퍼 타입의 일리스트로 변환하려고합니다 ....

public class FundParcel : Parcel
{
  /* properties defined here */
}

public class Parcel
{
  /* properties defined here */
}

이들은 다음과 같이 방법의 다른 클래스에서 사용됩니다.

private IList<Parcel> ExtractParcels(IEnumerable<FundParcel> fundParcels)
{
    var parcels = new List<Parcel>();

    foreach (var fp in fundParcels)
        parcels.Add(fp);

    return parcels;
}

내가 이해하지 못하는 것은 Foreach 문을 줄일 수없는 이유입니다.

parcels.AddRange(fundParcels);

기본적으로 "인수 유형"이라는 오류가 발생합니다. 'System.Colection.Generic.IEnumerable<FundParcel>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<Parcel>'"

하지만 그 경우에 왜 Parcels.add가 작동하는지 이해가 안 돼요 ...

마치 전체 방법이 라인으로 교체 할 수 있어야한다고 생각합니다.

return (List<Parcel>)fundParcels;

... 또는 하위 유형이 슈퍼 유형을 대체 할 수 있으므로 방법을 폐기 할 수 있습니다.

이 경우 addRange의 거래가 무엇인지 설명 할 수 있고이 경우 루프가 필요한 이유를 설명 할 수 있습니까?

도움이 되었습니까?

해결책

이렇게 아마도 당신의 질문에 대답 할 것이며, 다가오는 C# 4.0에 대한 참고 문헌을 어느 정도 지원할 수있는 참조를 지적 할 것입니다.

다른 팁

이 코드를 고려하십시오.

void AddParcelToParcelList(List<Parcel> parcels) {
  parcels.add(new Parcel());
}

List<FundParcel> fundParcels = new List<FundParcels>();
AddParcelToParcelList(fundParcels);

상속 클래스의 컨테이너가 기본 클래스의 컨테이너에서 상속 된 경우 위 코드가 유효하며 상속 클래스 목록에 기본 클래스의 객체가 포함 된 경우를 생성합니다.

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