我正试图通过使用此
来超载AgeDate DOB
getAge()
getAge(Date DOB)
把我不知道如何超载这种方法可以有人帮我吗?
public class Customer
{
private string CustomerID;
private string FirstName;
private string LastName;
private int Age;
private string Address;
private double phoneNumber;
public Customer(string CustomerID, string FirstName, string LastName, int Age, string Address, double phoneNumber)
{
this.CustomerID = CustomerID;
this.FirstName = FirstName;
this.LastName = LastName;
this.Age = Age;
this.Address = Address;
this.phoneNumber = phoneNumber;
}
public int age {get ; set; }
}
}
答案 0 :(得分:0)
要重载,请指定具有相同类型和名称但具有不同参数的方法。例如:
public int Foo(int bar)
{
return bar*2
}
public int Foo(string bar)
{
return bar.Length*2;
}
然后,当您引用Foo
方法时,您将获得1次重载,字符串参数为1。
然而,
你的类型的年龄部分不是方法,它是一个字段。字段不同,因为在实例化类型(var foo = new Person()
)时可以访问和编辑(取决于getter和setter)。
答案 1 :(得分:0)
我不确定你要问的是什么,但也许这可能会有所帮助,下面的示例显示了客户类构造函数的另一个重载,以及一个GetAge方法传递出生日期和返回年龄。
public class Customer
{
private string CustomerID;
private string FirstName;
private string LastName;
private int Age;
private string Address;
private double phoneNumber;
public Customer(string customerId, string firstName, string lastName, int age, string address, double phoneNumber)
{
this.CustomerID = customerId;
this.FirstName = firstName;
this.LastName = lastName;
this.Age = age;
this.Address = address;
this.phoneNumber = phoneNumber;
}
// overloading the Customer constructor passing in the 'Date of Birth' instead of the age
public Customer(string customerId, string firstName, string lastName, DateTime dateOfBirth, string address, double phoneNumber)
: this(customerId, firstName, lastName, GetAge(dateOfBirth), address, phoneNumber) // uses the previous constructor
{ }
public int age { get; set; }
// Calculating the age
private static int GetAge(DateTime dob)
{
var age = 0;
var today = DateTime.Today;
age = today.Year - dob.Year;
if (dob.AddYears(age) > today)// still has to celebrate birthday this year
age--;
return age;
}
}