2016-05-09 73 views
-5

我試圖用這個如何在C#中重載方法?

Date 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

'age'不是這裏的一種方法;它的一個屬性 –

+0

你試圖超載的方法是什麼?你的問題措辭的方式令人困惑。 – RScottCarson

+0

我想超載Age,但我不知道如何使用超載方法 – user5520587

回答

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()),可以訪問和編輯該字段(取決於獲取者和設置者)。

+0

它不必具有相同的返回類型。只是你不能*只改變返回類型。 –

+0

@JonSkeet哦,我認爲它只能通過參數名來區分。你會在哪裏更改退貨類型?我想不出任何時候我會這樣做...... – RhysO

+0

它會是這樣嗎? public int DOB(int Age) { return Age; } public int Age(int Age) { return年齡; } – user5520587

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