C# - DateTime Constructor Call

后端 未结 2 1482
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 13:01

So, I have this program that has a constructor with the inputs as DateTime.

But whenever I try to create the object of that Class, and pass the DateTime as argument, the

2条回答
  •  后悔当初
    2021-01-29 13:45

    Well yes - you're trying to pass three integer arguments to the constructor, but it accepts a DateTime value. You're not currently creating a DateTime value. All you need to do is change your constructor call to:

    var myprogram = new Student(new DateTime(1995, 4, 29));
    

    This will not happen implicitly - you need to tell the compiler that you really did mean to create a DateTime.

    As an alternative you could add a Student constructor to create the DateTime and chain to the other constructor:

    public Student(int year, int month, int day)
        : this(new DateTime(year, month, day))
    

    but that doesn't seem like a good idea to me for a Student class.

提交回复
热议问题