c#中Date类的创建不同类别

1.创建Date类, 类中具有年月日三个字段。以不同的方式创建对象(初始化器属性,构造函数以及对其重载。)
不同的方式有什么样的区别
2.在Date类中增加三个方法。天数增加一天,月份增加一月,年份增加一年,日期对象表示范围为21世纪。
三个不同的方法怎么添加

using System;
namespace ConsoleApp2
{
    public class Date
    {
        public int Year { get; set; }
        public int Month { get; set; }
        public int Day { get; set; }
        public Date() { }
        public Date(int Year, int Month, int Day)
        {
            this.Year = Year;
            this.Month = Month;
            this.Day = Day;
        }
        public void AddDay()
        {
            Day += 1;
            if (Month == 2) {
                var RN = (Year % 400 == 0 )|| (Year % 100 != 0 && Year % 4 == 0);
                if (Month > (RN ? 29 : 28)) AddMonth();
            }
            else if (Month == 1 || Month == 3 || Month == 5 || Month == 7 || Month == 8 || Month == 10 || Month == 12)
            {
                if (Day > 31)
                {
                    Day = 1;
                    AddMonth();
                }
            }
            else
            {
                if (Day > 30)
                {
                    Day = 1;
                    AddMonth();
                }
            }
        }
        public void AddMonth() {
            Month += 1;
            if (Month > 12)
            {
                AddYear();
                Month = 1;
            }
        }
        public void AddYear() {
            Year += 1;
        }
        public override string ToString()
        {
            return $"{Year}-{Month}-{Day}";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            var d1 = new Date { Year = 2022, Month = 12, Day = 19 };
            var d2 = new Date(2022, 12, 19);
            Console.WriteLine(d1);
            Console.WriteLine(d2);
            d2.AddMonth();
            Console.WriteLine(d2);
            Console.ReadKey();
        }
    }
}

望采纳

下面是 C# 中使用不同方式创建 Date 类的示例代码:

// 定义 Date 类,包含年、月、日三个字段
class Date
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }

    // 使用初始化器属性创建对象
    public Date(int year, int month, int day)
    {
        Year = year;
        Month = month;
        Day = day;
    }

    // 使用构造函数创建对象
    public Date()
    {
        Year = 1;
        Month = 1;
        Day = 1;
    }

    // 重载构造函数
    public Date(int year)
    {
        Year = year;
        Month = 1;
        Day = 1;
    }

    public Date(int year, int month)
    {
        Year = year;
        Month = month;
        Day = 1;
    }
}

不同的方式创建对象有以下区别:

使用初始化器属性创建对象时,需要在定义类时指定初始值。创建对象时,必须传入所有的初始值。
使用构造函数创建对象时,可以在定义类时指定默认值,也可以不指定默认值。创建对象时,可以不传入任何参数,也可以传入部分或全部的参数。
使用重载构造函数创建对象时,可以定义多个不同的构造函数,接受不同数量的参数。创建对象时,可以根据实际需要选择调用不同的构造函数

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632