gpt4 book ai didi

C# 在另一个 bool 方法中引用一个 bool 方法的返回值

转载 作者:行者123 更新时间:2023-11-30 22:58:54 26 4
gpt4 key购买 nike

我想知道如何在另一个方法中使用 bool 方法的结果。下面的代码包含两个方法,一个名为 ValidateDay,另一个名为 IsLeapYearIsLeapYear 确定用户输入的整数是否为闰年。 ValidateDay 根据用户输入的月份检查用户输入的日期是否有效。为了检查 2 月 29 日是否有效,我需要 ValidateDay 方法来了解 IsLeapYear 的结果是真还是假。但是,我不确定如何在 ValidateDay 方法中引用 IsLeapYear 的返回值。任何建议将不胜感激。

// Determines if day is valid
public Boolean ValidateDay()
{
IsLeapYear();

if(Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
{
if (Day >= 1 && Day <= 31)
{
return true;
}
else
{
return false;
}
}
else if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
{
if (Day >= 1 && Day <= 30)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && IsLeapYear(true))
{
if (Day >= 1 && Day <= 29)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && IsLeapYear(false))
{
if (Day >= 1 && Day <= 28)
{
return true;
}
else
{
return false;
}
}
}

// Determine if year is a leap year
public Boolean IsLeapYear()
{
if ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0))
{
return true;
}
else
{
return false;
}
}

最佳答案

在下一行中,您将值 true 传递给 IsLeapYear() 方法:

else if (Month == 2 && IsLeapYear(true))

但是您的 IsLeapYear() 方法没有参数,我猜您打算在这里做的是评估 IsLeapYear() 的结果是否为真。只需将其更改为以下内容:

else if (Month == 2 && IsLeapYear() == true)

或更简洁:

else if (Month == 2 && IsLeapYear())

要检查该值是否为 false,只需使用 !要评估的表达式之前的字符:

else if (Month == 2 && !IsLeapYear())

或者如果您愿意:

else if (Month == 2 && IsLeapYear() == false)

关于C# 在另一个 bool 方法中引用一个 bool 方法的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52656522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com