下面的代码我想要做什么,除了实在是太硬编码的事实,会显示建筑材料与值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 –