有没有办法简化以下代码? 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 });
}
答案 0 :(得分:3)
这看起来像是一个溺水问题:您的Bank
,Currency
和Amount
类型具有相同的成员(Id
,Name
,和Code
)但没有共同的层次结构。
解决方案是创建一个新的interface
(我称之为ICurrencyBankOrAmount
),声明这些成员,然后将界面添加到Bank
,Currency
和{ {1}}模型类,然后你可以有一个循环体 - 我已经为你将它转换为Linq表达式:
Amount
如果您无法修改这些类,则可以使用适配器模式。
答案 1 :(得分:2)
确保您的类实现了一个通用接口。
public void FillCollection(IReadOnlyList<ISomeDescriptiveNameHere> supportList) {
foreach (var temp in supportList) {
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 });
}
}
然后你可以写
List<T>
这依赖于IReadOnlyList<T>
实现IReadOnlyList<T>
,而T
在IReadOnlyList<U>
中是协变的事实,这意味着它可以透明地传递为U
其中{ {1}}是T
的任何基类或实现的接口。