下面的代碼我想要做什麼,除了實在是太硬編碼的事實,會顯示建築材料與值0。現在,它可能會顯示如何過濾字符串不IF語句C#
木:100% ,砌體:0%,混凝土:0%,鋼:0%,輕金屬:0%,移動房屋:0%,其他:0%,未知:0%
我希望在這種情況下顯示
木:100%
我是一個極端的業餘,我知道該怎麼做THI的唯一途徑s有10000個IF語句,但必須有更優雅的方式。函數convertFIRE是映射到這些主要結構「桶」
for (int row = firstrow + 1; row <= sheet5.LastRowNum; row++)
{
convertFIRE(sheet5.GetRow(row).GetCell(1).ToString());
if (constructioncode == "Wood")
{
wood = wood + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Masonry")
{
masonry = masonry + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Concrete")
{
concrete = concrete + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Steel")
{
steel = steel + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Light Metal")
{
lghtmetal = lghtmetal + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Mobile Home")
{
mobilehome = mobilehome + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Other")
{
other = other + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
else if (constructioncode == "Unknown")
{
unknowncode = unknowncode + sheet5.GetRow(row).GetCell(10).NumericCellValue;
}
}
constructiontext = "Wood: " + String.Format("{0:P1}", wood) + ", " + "Masonry: " + String.Format("{0:P1}", masonry) + ", " + "Concrete: " + String.Format("{0:P1}", concrete) + ", "
+ "Steel: " + String.Format("{0:P1}", steel) + ", " + "Light Metal: " + String.Format("{0:P1}", lghtmetal) + ", " + "Mobile Home: " + String.Format("{0:P1}", mobilehome) + ", " + "Other: " + String.Format("{0:P1}.", other) + ", " + "Unknown: " + String.Format("{0:P1}", unknowncode);
我想你應該閱讀http://www.codinghelmet.com/?path=howto/poor-mans-polymorphism-or-whats-so-wrong-about-if-那麼 - 否則 –
應該可能去Review.StackExchange.com,不是嗎? – HimBromBeere
@HimBromBeere我不太確定現在「重構此代碼」是否會成爲[CodeReview.SE]的主題,但您是對的 - 在過去,完全相同的問題是確定的 - http://codereview.stackexchange .com/questions/46530/how-to-refactor-multiple-if-statements –