c# – 如何使通用列表等于另一个通用列表
发布时间:2020-12-15 06:23:47 所属栏目:百科 来源:网络整理
导读:这是我的设置, 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; }
这是我的设置,
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 } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容