C#简单构造函数重载

时间:2014-05-27 06:20:00

标签: c#

我正在进行一个非常简单的重载构造函数练习,但是遇到了没有重载的参数。我以为我做得对,但也许我做错了什么?

   namespace A3_Date_StudentWork
    {
        class MyDate
        {      


            private int newMonth;
            private int newDay;
            private int currentMonth;
            private int currentDay;

            public MyDate(int month, int day)
            {
               newMonth = month;
               newDay = day;
            }

            public MyDate(int month, int day, int cmonth, int cday)
            {
                newMonth = month;
                newDay = day;
                currentMonth = cmonth;
                currentDay = cday;
            }
        }
    }

以下是我的新对象从主

看起来的样子
    MyDate today = new MyDate(todayMonth, todayDay);

    MyDate bday = new MyDate(bdayMonth, bdayDay);

    MyDate combine = new MyDate(bdayMonth, bdayDay, todayMonth, todayDay);

这是非常简单的程序,我的所有变量都是int。我的整个主要:

    static void Main(string[] args)
    {

        int todayMonth = 0;
        int todayDay = 0;
        int bdayMonth = 0;
        int bdayDay = 0;


        Console.WriteLine("What is today's month?");
        Int32.TryParse(Console.ReadLine(), out todayMonth);
       // Console.WriteLine(todayMonth);

        Console.WriteLine("What is today's date?");
        Int32.TryParse(Console.ReadLine(), out todayDay);
       // Console.WriteLine(todayDay);

        Console.WriteLine("What is your birth month?");
        Int32.TryParse(Console.ReadLine(), out bdayMonth);
       // Console.WriteLine(bdayMonth);

        Console.WriteLine("What is your birth date?");
        Int32.TryParse(Console.ReadLine(), out bdayDay);
       // Console.WriteLine(bdayDay);

        MyDate today = new MyDate(todayMonth, todayDay);
        MyDate bday = new MyDate(bdayMonth, bdayDay);
        MyDate combine = new MyDate(bdayMonth, bdayDay, todayMonth, todayDay);

这是带有构造函数的基类

    {
class MyDate
{      


    private int newMonth;
    private int newDay;
    private int currentMonth;
    private int currentDay;

    public MyDate(int month, int day)
    {
       newMonth = month;
       newDay = day;
    }

    public MyDate(int month, int day, int cmonth, int cday)
    {
        newMonth = month;
        newDay = day;
        currentMonth = cmonth;
        currentDay = cday;
    }

基类实际上是MyDate类

1 个答案:

答案 0 :(得分:3)

这里只是技术方面的一条建议。 当你有多个构造函数时,你应该从一个构造函数调用另一个构造函数,如果可能的话,通过传递值。这也称为“构造链接”。

以下是基于您的代码的示例:

class MyDate
{
    private int newMonth;
    private int newDay;
    private int currentMonth;
    private int currentDay;

    public MyDate(int month, int day)
       : this(month, day, 0, 0)
    { }

    public MyDate(int month, int day, int cmonth, int cday)
    {
        newMonth = month;
        newDay = day;
        currentMonth = cmonth;
        currentDay = cday;
    }
}

在这种简单的情况下,当您使用2个参数(月和日)调用构造函数时,其他参数默认为0。您还可以使参数为可为空,以便为其指定空值。