【问题标题】:Creating and using Constructors in C# along with Boolean methods在 C# 中创建和使用构造函数以及布尔方法
【发布时间】:2019-03-11 05:06:21
【问题描述】:

我在 C# 赋值中的构造函数遇到了一些问题。下面的第一个代码块包含一些赋值指令。本质上,据我了解,我将创建两个构造函数,一个用于设置默认日期,另一个用于检查用户的日期。此外,还有一个 SetDate 方法似乎在做同样的事情。这些似乎是多余的,但根据分配说明,两者都是必需的。我对面向对象编程非常陌生,所以我不确定如何将东西“传递”给构造函数,或者真正如何使用它并在 main 方法中调用它。第二个代码块是我到目前为止所写的。所有日期验证方法似乎都很好。但是,我不知道如何处理 public Date(int M, int D, int Y) 构造函数和 SetDate 方法。这些都应该做什么?另外,当我还被告知在上面声明月、日和年时,为什么我被指示使用整数变量 M、D、Y?任何可能有助于我理解如何使用此构造函数以及它与SetDate 方法在功能上有何关联和不同之处的见解将不胜感激。

 //Create a Date Class
 //This class holds:
private int Month;
private int Day;
private int Year;
    //Include the following constructors/methods. Include others/more if you 
    //need them.

    // Sets date to 1/1/1900
public Date()

    // Sets date to user’s input.
    // Checks to see the date is valid
    // If it isn’t valid, print message and set date to 1/1/1900
public Date(int M, int D, int Y)

     // Sets date to user’s input.
     // Checks to see the date is valid
     // If it isn’t valid, print message and set date to 1/1/1900
public Boolean SetDate(int M, int D, int Y)ere

//*************************************************** ******************************************

class Date
{
    private int Month;
    private int Day;
    private int Year;

    // Sets date to 1/1/1900
    public Date()
    {
        Month = 1;
        Day = 1;
        Year = 1900;
    }

    public Date(int M, int D, int Y)
    {
        Month = M;
        Day = D;
        Year = Y;
    }

    public Boolean SetDate(int M, int D, int Y)
    {

        int valDate = 0;

        Console.WriteLine("You will be prompted to enter three(3) numbers to represent a month, " +
            "day, and year. Only dates between 1/1/1900 and 12/31/2100 are valid.");

        Console.WriteLine("");

        while (valDate < 1)
        {
            Console.WriteLine("Enter the number for the month.");
            M = int.Parse(Console.ReadLine());
            Console.WriteLine("");

            Console.WriteLine("Enter the number for the day.");
            D = int.Parse(Console.ReadLine());
            Console.WriteLine("");

            Console.WriteLine("Enter the number for the year.");
            Y = int.Parse(Console.ReadLine());
            Console.WriteLine("");

            ValidateDate();

            if (ValidateDate())
            {
                DisplayDate();
                valDate++;
                return true;
            }
            else
            {

                Console.WriteLine("Please enter a valid date.");
                Console.WriteLine("");
                Month = 1;
                Day = 1;
                Year = 1900;
                return false;
            }


        }
        return false;
    }
        // Determines if date is valid.
    public Boolean ValidateDate()
    {
        ValidateMonth();
        ValidateDay();
        ValidateYear();

        if (ValidateMonth() && ValidateDay() && ValidateYear())
        {
            return true;
        }
        else
        {
            return false;
        }


    }
        // Determines if month is valid.
    public Boolean ValidateMonth()
    {
        if (Month >= 1 && Month <= 12)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
        // Determines if year is valid.
    public Boolean ValidateYear()
    {
        if(Year >= 1900 && Year <= 2100)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
        // Determines if day is valid
    public Boolean ValidateDay()
    {
        IsLeapYear();

        if(Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
        {
            if (Day >= 1 && Day <= 31)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (Month == 4 || Month == 6 || Month == 9 || Month == 11)
        {
            if (Day >= 1 && Day <= 30)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (Month == 2 && IsLeapYear())
        {
            if (Day >= 1 && Day <= 29)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else if (Month == 2 && !IsLeapYear())
        {
            if (Day >= 1 && Day <= 28)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    // Determine if year is a leap year
    public Boolean IsLeapYear()
    {
        if ((Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

        // Print date to screen in format M/D/Y
    public void DisplayDate()
    {
        Console.WriteLine(ShowDate());
    }

    public String ShowDate()
    {
        StringBuilder myStringBuilder = new StringBuilder();
        myStringBuilder.AppendFormat("{0} / {1} / {2}", Month, Day, Year);
        return (myStringBuilder.ToString());
    }

    static void Main(string[] args)
    {
        Date NewDate = new Date();
        NewDate.Date();

        Console.ReadLine();
    }
}

【问题讨论】:

    标签: c# object methods constructor boolean


    【解决方案1】:

    如果您想使用日期制作一些真正的应用程序,那么我建议您查看 System 命名空间中的 DateTime 结构。这有TryParse 函数,无论输入是否有效,它都会返回真或假。

    但是,您似乎正在做一些编程练习,所以在这种情况下,我的答案是:在构造函数中包含可能导致无效对象的参数并不是很好——在您的情况下,日期无效。这是因为一旦调用构造函数,您将以一种或另一种方式拥有一个对象,除非您在构造函数中抛出异常。然而,如果你仍然想拥有它,那么你需要在类/结构中有一个名为“IsValid”的属性或公共变量,它告诉构造函数是否给出了有效日期。 更好的选择是遵循 DateTime 方法 - 有一个返回有效 Date 对象的公共静态函数。像这样:

    public bool TryParse(int m, int d, int y, out Date date)
    {
       // validate
    
       // if valid then return Date object like that:
       date = new Date()
       {
          Month = m,
          Day = d,
          Year = y
       };
       return true;
    
       // Or like that:
       date = new Date(m, d, y);
       return true;
    
       // if not valid then return null (because have to return something)
       date = null;
       return false;
    }
    

    【讨论】:

    • 这是非常好的信息,谢谢。但是,对于我正在做的练习,我需要使用列出的构造函数或方法。我不确定在 public Date(int M, int D, int Y) 构造函数中放入什么,因为根据说明,它看起来与 SetDate 方法完全相同。同样,这两个对象都是程序所必需的。
    【解决方案2】:

    您似乎被要求创建一个执行相同操作的方法和构造函数。在这种情况下,最简单的做法是让构造函数调用该方法。

    我对您的代码的唯一评论是您显示的问题陈述不需要在 SetDate 方法中收集输入。鉴于该声明,用户的输入似乎会在您的班级之外收集。

    我不知道您对失败消息的要求是什么。这在它自己的方法中也可能有意义。

    这是一个例子:

    public class Date
    {
        private int Month;
        private int Day;
        private int Year;
    
        public Date()
        {
            SetDefaultDate();
        }
    
        public Date(int M, int D, int Y)
        {
            SetDate(M, D, Y);
        }
    
        public void SetDate(int M, int D, int Y)
        {
            if (IsValidDate(M, D, Y))
            {
                Month = M;
                Day = D;
                Year = Y;
            }
            else
            {
                SetDefaultDate();
            }
        }
    
        private bool IsValidDate(int M, int D, int Y)
        {
            // validation logic.. return true if all parameters result in valid date
            // false if they do not.  If it is an invalid date print the failure message.
    
            return true;
        }
    
        private void SetDefaultDate()
        {
            Month = 1;
            Day = 1;
            Year = 1900;
        }
    }
    

    【讨论】:

    • 这很有帮助。谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2016-06-19
    • 2013-04-29
    • 2020-11-11
    相关资源
    最近更新 更多