这是我的设置,
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 } } }
这样做的最佳方式是什么?
解决方法
使用Cast< IPeriodCalculation>():
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,如果你正在使用实现IEnumerable< out T>的东西,你可以按照你编写它的方式来做,它将使用Covariance来解决.
class myDto { public IEnumerable<CostPeriodDto> costPeriodList{ get; set; } public IEnumerable<IPeriodCalculation> periodCalcList { get { return this.costPeriodList; // wont give a compilation error } } }