2010-02-03 21 views
6

,Nasıl yapmak için başka bir genel listeye Bu benim kurulur

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 
     } 
    } 
} 

Ne Bunu yapmanın en iyi yolu olacak bir genel liste eşit?

cevap

3

return this.costPeriodList.Cast<IPeriodCalculation>().ToList()'u deneyin.

9

Kullanım Cast<IPeriodCalculation>(): Eğer IEnumerable<out T> uygulayan bir şey kullanıyormuş

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();   
     } 
    } 
} 

Ben, C# 4 inanıyoruz, bunu sen yazdın şekilde yapmak sadece olabilir ve bu Covariance kullanılarak çözüleceğini.

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

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

LINQ yöntemleri eşit olmayacak başka bir diziden döküm. Yani, Cast()/ToList()'u kullandıysanız aşağıdaki sınama başarısız olur.

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

Dahası, bu yöntemleri kullanarak tek bir koleksiyona bir öğe eklemek çalışırsa, diğer yansıyan olmaz demektir. Ve ne zaman periodCalcList çağırdı, kaç öğe, ne sıklıkta denir, vb. Bağlı olarak felaket olabilir tamamen yeni bir koleksiyon yaratacaktır.

Benim düşünceme göre daha iyi bir çözüm List<T> CostPeriodDto tutuyor ve bunun yerine Collection<T>'dan türetilmiş bir koleksiyonu kullanın ve IEnumerable<IPeriodCalculation>'u açıkça uygulayın. Gerektiğinde, gerekirse IList<IPeriodCalculation>'u uygulayabilirsiniz.

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; } 
    } 
} 
İlgili konular