C#-DateTime构造函数调用 [英] C# - DateTime Constructor Call
问题描述
因此,我有一个程序,该程序的构造函数的输入为DateTime。
So, I have this program that has a constructor with the inputs as DateTime.
但是每当我尝试创建该Class的对象并传递DateTime时,
But whenever I try to create the object of that Class, and pass the DateTime as argument, there is an error.
代码如下:
public Student(DateTime dob)
{
DateofBirth = dob;
}
}
class Program
{
static void Main(string[] args)
{
var myprogram = new Student(1995,04,29);
但是,在Student类中显示错误,表明构造函数不能接受三个参数。
But, it's showing error in the Student class stating that constructor cannot take three arguments. Please help!
PS:上面和下面都有代码,因此请忽略括号。
PS: There is code above and below, so ignore the brackets.
推荐答案
是的-您正试图将三个整数参数传递给构造函数,但它接受 DateTime
值。您当前未创建 DateTime
值。您需要做的就是将构造函数调用更改为:
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));
这将不隐式发生-您需要告诉编译器 did 的意思是创建一个 DateTime
。
This will not happen implicitly - you need to tell the compiler that you really did mean to create a DateTime
.
作为替代,您可以添加一个 Student
构造函数来创建 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))
但是对于 Student
类。
这篇关于C#-DateTime构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!