问题描述
什么是正确的转换方式
if((year mod 4=0 and year mod 100<>0) or (year mod 400=0),“Leap Year”,“Not a Leap Year”)
致C#
我能够成功转换第一部分 if ((year % 4 == 0 & year % 100 != 0) | (year % 400 == 0))
,但是添加消息时出现错误。
任何帮助将不胜感激。
解决方法
该VB If
运算符的等效项是C#ternary operator(?:
),即
If(x,y,z)
等效于:
x ? y : z;
为了记录,还有另一个If
运算符,如下所示:
If(x,y)
如果x
不是x
,则的取值为null
,否则为y
。 C#等效项称为null coalescing operator(??
):
x ?? y;
,
原始的VB代码应使用DateTime.IsLeapYear(Int32) Method,以便在C#中变为:
DateTime.IsLeapYear(year) ? "Leap Year" : "Not a Leap Year";
,
可编译代码的答案是:
private string LeapYearResponse(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return "Leap Year";
else
return "Not a Leap Year";
}
或更简洁地说:
private string LeapYearResponse(int year)
{
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) ? "Leap Year" : "Not a Leap Year";
}