这是我的设置
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
}
}
}