我如何在 C# 中重载方法?

How can i Overload Method in c#?

我正试图通过使用这个

来超载 Age
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; }
}
}

要重载,您需要指定一个具有相同类型和名称但具有不同参数的方法。例如:

public int Foo(int bar)
{
  return bar*2
}

public int Foo(string bar)
{
  return bar.Length*2;
}

然后当你引用Foo方法时,你得到1个重载,字符串参数一个。

然而,

类型的年龄部分不是方法,而是字段。字段是不同的,因为它可以在您实例化类型时访问和编辑(取决于 getter 和 setter)(var foo = new Person())。

我不太确定你在问什么,但也许这会有所帮助,下面的示例显示了客户 class 构造函数的另一个重载,以及一个传递出生日期的 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;
    }
}