2010-02-03 1 views
6

,어떻게 만들려면 다른 일반적인 목록이가 내 설정

class CostPeriodDto : IPeriodCalculation 
{ 
    public decimal? a { get; set; } 
    public decimal? b { get; set; } 
    public decimal? c { get; set; } 
    public decimal? d { get; set; } 
} 

interface IPeriodCalculation 
{ 
    decimal? a { get; set; } 
    decimal? b { get; set; } 
} 

class myDto 
{ 
    public List<CostPeriodDto> costPeriodList{ get; set; } 

    public List<IPeriodCalculation> periodCalcList 
    { 
     get 
     { 
      return this.costPeriodList; // compile error 
     } 
    } 
} 

무엇이 일을하는 가장 좋은 방법이 될 것입니다 일반적인 목록과 동일?

답변

3

시도 return this.costPeriodList.Cast<IPeriodCalculation>().ToList().

9

사용 Cast<IPeriodCalculation>() : 당신이 IEnumerable<out T>를 구현하는 것을 사용한다면

public class CostPeriodDto : IPeriodCalculation 
{ 
    public decimal? a { get; set; } 
    public decimal? b { get; set; } 
    public decimal? c { get; set; } 
    public decimal? d { get; set; } 
} 

public interface IPeriodCalculation 
{ 
    decimal? a { get; set; } 
    decimal? b { get; set; } 
} 

public class myDto 
{ 
    public List<CostPeriodDto> costPeriodList { get; set; } 

    public List<IPeriodCalculation> periodCalcList 
    { 
     get 
     { 
      return this.costPeriodList.Cast<IPeriodCalculation>().ToList();   
     } 
    } 
} 

내가, C# 4 믿고, 당신은 당신이 그것을 쓴 방법을 간단하게 할 수, 그것은 Covariance를 사용하여 해결 될 것입니다.

class myDto 
{ 
    public IEnumerable<CostPeriodDto> costPeriodList{ get; set; } 

    public IEnumerable<IPeriodCalculation> periodCalcList 
    { 
     get 
     { 
      return this.costPeriodList; // wont give a compilation error  
     } 
    } 
} 
1

LINQ 방법 동일되어야 다른 하나의 시퀀스에서 전송. 즉, Cast()/ToList()을 사용하면 다음 테스트가 실패합니다.

Assert.AreSame(myDto.costPeriodList, myDto.periodCalcList); 

또한 이러한 방법을 사용하면 항목을 하나의 컬렉션에 추가하려고하면 다른 컬렉션에 항목이 반영되지 않습니다. 그리고 periodCalcList를 호출 할 때마다 항목 수, 호출 빈도 등에 따라 완전히 새로운 콜렉션이 작성됩니다.

더 나은 해결책은 내 의견으로는 List<T>을 사용하지 않는 것입니다. CostPeriodDto를 잡고 대신 Collection<T>에서 파생 된 모음을 사용하고 IEnumerable<IPeriodCalculation>을 명시 적으로 구현합니다. 원하는 경우 IList<IPeriodCalculation>을 구현할 수도 있습니다.

class CostPeriodDtoCollection : 
    Collection<CostPeriodDto>, 
    IEnumerable<IPeriodCalculation> 
{ 

    IEnumerable<IPeriodCalculation>.GetEnumerator() { 
     foreach (IPeriodCalculation item in this) { 
      yield return item; 
     } 
    } 

} 

class MyDto { 
    public CostPeriodDtoCollection CostPeriods { get; set; } 
    public IEnumerable<IPeriodCalculation> PeriodCalcList { 
     get { return CostPeriods; } 
    } 
} 
관련 문제