有什麼辦法可以簡化下面的代碼嗎? supportList是從構造函數得到一個對象:簡化c#if/else語句與不同List <>
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 });
}
您的//代碼在這裏對於所有三個語句塊都是相同的嗎? – Amit
爲什麼不使用泛型? –
是的。你通過不這樣做來簡化這一點。你應該*做什麼,我們不能說。也許[編輯]並描述你的目標是在這裏? – Will