如何使用 StudentId = 1 和 Name = "Alex"初始化这样的类
class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public Student(Student student)
{
StudentId = student.StudentId;
Name = student.Name;
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student()
}
}
最佳答案
您可以添加另一个构造函数,您可以在其中手动提供值:
public Student(int id, string name)
{
StudentId = id;
Name = name;
}
您的初始代码不起作用的原因是,当您创建一个需要相同类型的另一个实例的对象时,依赖链会上升到无穷大,您永远无法找到起点。
有了手动构造函数,你可以手动创建一个起点,换句话说,一个初始对象,其他对象可以依赖。因此,您消除了无限依赖链。
关于c# - 在同一类的构造函数中传递类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47144586/