C#在另一个布尔方法中引用布尔方法的返回值
我想知道如何在另一个方法中使用布尔方法的结果。下面的代码包含两个方法,一个名为C#在另一个布尔方法中引用布尔方法的返回值,c#,C#,我想知道如何在另一个方法中使用布尔方法的结果。下面的代码包含两个方法,一个名为ValidateDay,另一个名为IsLeapYearIsLeapYear确定用户输入的整数是否为闰年ValidateDay根据用户输入的月数检查用户输入的日期是否有效。为了检查2月29日是否有效,我需要使用ValidateDay方法来了解IsLeapYear的结果是真是假。但是,我不确定如何在ValidateDay方法中引用IsLeapYear的返回值。任何建议都将不胜感激 // Determines if day
ValidateDay
,另一个名为IsLeapYear
<代码>IsLeapYear确定用户输入的整数是否为闰年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;
}
}
//确定日期是否有效
公共布尔ValidateDay()
{
IsLeapYear();
如果(月=1 |月=3 |月=5 |月=7 |月=8 |月=10 |月=12)
{
如果(Day>=1&&Day=1&&Day=1&&Day=1&&Day我认为您可以尝试使用IsLeapYear()
和!IsLeapYear()
来检查是否是闰年
else if (Month == 2 && IsLeapYear())
{
if (Day >= 1 && Day <= 29)
{
return true;
}
else
{
return false;
}
}
else if (Month == 2 && !IsLeapYear())
{
if (Day >= 1 && Day <= 28)
{
return true;
}
else
{
return false;
}
}
DateTime.IsLeapYear(year)
在下一行中,将值true
传递给IsLeapYear()方法:
但是您的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)
我确实觉得你把事情复杂化了一点
尝试以下方法:
public Boolean ValidateDay()
{
try
{
return Day >= 1 && Day <= DateTime.DaysInMonth(Year, Month);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}
public Boolean IsLeapYear()
{
try
{
return DateTime.IsLeapYear(Year);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}
public Boolean ValidateDay()
{
尝试
{
return Day>=1&&DayBoolean isLeap=IsLeapYear();
那么你可以在if语句中使用isLeapelse if(Month==2&&isLeap)
和else if(Month==2&&isLeap)/!表示不
,当然你可以在if语句中调用methode diretcly`else if(Month==2&&IsLeapYear())`和`else if(Month==2&&IsLeapYear())`如果(Month==2&&isLeap)
等于(Month==2&&isLeap==false)
和如果(Month==2&&isLeap)
等于如果(Month==2&&isLeap==true)
public Boolean ValidateDay()
{
try
{
return Day >= 1 && Day <= DateTime.DaysInMonth(Year, Month);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}
public Boolean IsLeapYear()
{
try
{
return DateTime.IsLeapYear(Year);
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}