切换elseif切换案例

我们如何切换下面的if -else语句来切换case语句..任何人都可以帮忙…

if (Webcc1.Contains(licensePartID)) { dtExpiryDate = dtActivatedDate.AddYears(1); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; } } else if (Webcc3.Contains(licensePartID)) { dtExpiryDate = dtActivatedDate.AddYears(3); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; } } else if (Webcc5.Contains(licensePartID)) { dtExpiryDate = dtActivatedDate.AddYears(5); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; } } 

提前谢谢了 ….

您无法直接执行此操作,但您可以使用按位运算三元条件将if … else if转换为switch语句:

 var flags = (Webcc1.Contains(licensePartID)) ? 1 : 0; flags |= (Webcc3.Contains(licensePartID)) ? 2 : 0; flags |= (Webcc5.Contains(licensePartID)) ? 4 : 0; 

 var flags = (Webcc1.Contains(licensePartID)) ? 1 : (Webcc3.Contains(licensePartID)) ? 2 : (Webcc5.Contains(licensePartID)) ? 4 : 0; switch(flags) { case 1: dtExpiryDate = dtActivatedDate.AddYears(1); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; } break; case 2: dtExpiryDate = dtActivatedDate.AddYears(3); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; } break; case 4: dtExpiryDate = dtActivatedDate.AddYears(5); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; } break; } } 

但是,您提供的代码示例可以并且应该更短,因为在条件之间唯一更改的是添加的年数,您可以简单地执行此操作:

 var numberOfYears = (Webcc1.Contains(licensePartID)) ? 1 : (Webcc3.Contains(licensePartID)) ? 3 : (Webcc5.Contains(licensePartID)) ? 5 : 0; // or some other default number if needed dtExpiryDate = dtActivatedDate.AddYears(numberOfYears); int isExpiry = DateTime.Compare(dtActivatedDate, dtExpiryDate); if (isExpiry >= 0) { setError(lblSystemErr, "This action cannot be performed. The subscription period of the license key has expired"); return; }