有什么办法可以简化下面的代码吗?supportList 是一个从构造函数获取的对象:
public void FillCollection(object supportList)
代码在这里:
if (supportList is List<Bank>)
{
foreach (var temp in supportList as List<Bank>)
{
//code here
}
}
else if (supportList is List<Currency>)
{
foreach (var temp in supportList as List<Currency>)
{
//code here
}
}
else if (supportList is List<Amount>)
{
foreach (var temp in supportList as List<Amount>)
{
//code here
}
}
编辑 1:所有 foreach 部分都执行相同的代码,例如
foreach (var temp in supportList as List<Bank>)
{
string yesno;
if (temp.Id == CurrentId)
{
yesno = "" + yes;
}
else
{
yesno = "" + no;
}
CollectionSupport.Add(new SupportModel { Id = temp.Id, Name = temp.Name,
Code = temp.Code, YesNo = "" + yesno });
}
这看起来像一个鸭打字的问题:在您Bank
,Currency
和Amount
类型有相同的成员(Id
,Name
,和Code
),但不共享同一层次。
一个解决方案是创建一个新的interface
(我把它叫做ICurrencyBankOrAmount
)的声明这些成员,然后将接口添加到您Bank
,Currency
和Amount
模型类,那么你可以有一个循环体-我已经低于它转换成一个LINQ表达式为你:
public void FillCollection<TItem>(List<TItem> supportList)
where TITem : ICurrencyBankOrAmount
{
this.CollectionSupport.AddRange(
supportList
.Select( item => new SupportModel()
{
Id = item.Id,
Name = item.Name,
Code = item.Code,
YesNo = item.Id == this.CurrentId ? "yes" : "no"
} )
)
}
如果您无法修改这些类,则可以使用适配器模式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句