如何使通用列表等于另一个通用列表

Sim*_*ght 6 c#

这是我的设置,

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   
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做的最佳方式是什么?

Dyn*_*ard 9

用途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();         
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我相信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    
        } 
    } 
} 
Run Code Online (Sandbox Code Playgroud)


Joh*_*lla 3

尝试return this.costPeriodList.Cast<IPeriodCalculation>().ToList()