VB 到 C# 的转换错误(赋值和 if 语句)

VB to C# conversion error (assign and if statements)

正确的转换方式是什么

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 不是 null,则计算结果为 x,否则计算结果为 y。 C# 等效项称为 null coalescing operator (??):

x ?? y;

可编译代码中的答案是:

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";
}

原来的VB代码应该使用了DateTime.IsLeapYear(Int32) Method,这样在C#中就会变成:

DateTime.IsLeapYear(year) ? "Leap Year" : "Not a Leap Year";