本文介绍了切换 elseif 切换大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何将下面的 if -else 语句切换为 switch case 语句.. 任何人都可以帮助解决这个问题...
How can we switch the below if -else statements to switch case statement .. can anyone help on this ...
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 语句:
You can't do it directly, but you can use a ternary condition to convert your if...else if into a switch statement:
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;
}
}
但是,您提供的代码示例可以而且应该更短,因为条件之间唯一改变的是要添加的年数,您可以简单地这样做:
However, the code sample you provided can and should be shorter, since the only thing that is changed between the conditions is the number of years to add, you can simply do this:
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;
}
这篇关于切换 elseif 切换大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!