gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:03:27 24 4
gpt4 key购买 nike

这是我的设置,

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

关于c# - 如何使通用列表等于另一个通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2189720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com