我对编码非常陌生,目前正在尝试学习C#。作为一个小型项目/实践,我试图创建一个迷你地址簿,作为其中的一部分,我想从出生日期和今天计算年龄。我收集此日期的代码如下:
DateTime today = DateTime.Today;
public int age(DateTime today, DateTime birthDate)
{
if (today.Month < this.birthDate.Month)
{
return ((today.Year - this.birthDate.Year) - 1);
}
else if (today.Month == this.birthDate.Month )
{
if (today.Day >= this.birthDate.Day)
return (today.Year - this.birthDate.Year);
else
return ((today.Year - this.birthDate.Year) - 1);
}
else
return (today.Year - this.birthDate.Year);
}
但是,当我尝试拨打Console.WriteLine(person.age)
或对我的任何person.age
做任何事情时,它会告诉我
最佳重载方法匹配&#39; System.Console.WriteLine(string,params object [])&#39;有一些无效的论点。
然而,尽管我已经尝试过,但我无法弄清楚我做错了什么。
答案 0 :(得分:2)
age
是一种方法,您可以将其称为属性。
执行以下操作:
person.age(today, birthday);
或将其转换为属性,这可能是您想要的:
public int Age
{
get
{
var today = DateTime.Now;
if (today.Month < this.birthDate.Month)
{
return ((today.Year - this.birthDate.Year) - 1);
}
else if (today.Month == this.birthDate.Month )
{
if (today.Day >= this.birthDate.Day)
return (today.Year - this.birthDate.Year);
else
return ((today.Year - this.birthDate.Year) - 1);
}
else
return (today.Year - this.birthDate.Year);
}
}
答案 1 :(得分:2)
Console.WriteLine(person.age(today, birthday).ToString());
答案 2 :(得分:0)
看起来你已经忘记包含这些参数了,你今天已经在你的方法之外进行了初始化,但是你也需要一个生日,那么只需将它传入:
person.age(today, birthday);
答案 3 :(得分:-1)
错误表明您向函数传递了错误的参数或较少的参数。要解决此问题,您必须修改如下
Console.WriteLine(&#34;此人的年龄为{0}&#34;,person.age);