您好我正在做一个c#课程,无法理解构造函数调用主题。我得到错误并一直在看视频,但我无法让它工作,我不断收到错误:“E2.Student.Student(string,string)'不能自称”
当我尝试创建一个带有2个参数的构造函数时,我得到了这个错误,因为我理解这个带有我试图创建的2个参数的构造函数是否继承了它下面的4个参数的构造函数?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace E2
{
class Student
{
string fullName;
string course;
string email;
string phonenr;
enumUniversity university;
enumSubject subject;
public Student()
{
}
public Student(string fullname,string course) : this (fullname,course) =======>THIS IS WHERE I GET THE ERROR
{
}
public Student(string fullname, string course, string email, string phonenr, enumUniversity university, enumSubject subject)
{
this.fullName = fullname;
this.course = course;
this.email = email;
this.phonenr = phonenr;
this.university = university;
this.subject = subject;
}
public void PrintInfo()
{
Console.WriteLine("Name: {0} Course {1} email {2} phonenr {3} univ {4} subject {5}", fullName, course, email, phonenr, university, subject);
}
}
}
我的学习内容示例:
public Dog(string name)
: this(name, 1) // Constructor call
{
}
// Two parameters
public Dog(string name, int age)
: this(name, age, 0.3) // Constructor call
{
}
// Three parameters
public Dog(string name, int age, double length)
: this(name, age, length, new Collar()) // Constructor call
{
}
// Four parameters
public Dog(string name, int age, double length, Collar collar)
{
this.name = name;
this.age = age;
this.length = length;
this.collar = collar;
}
答案 0 :(得分:1)
让构造函数使用ctor链接调用自身。这种情况是不可能的,因为它会导致世界变成某种无限循环:)
执行此操作的方法是,您需要使用所有其他参数调用构造函数,例如:
public Student() : this(string.Empty, string.Empty)
{
}
public Student(string fullname,string course)
: this (fullname,course, string.Empty, string.Empty, default(enumUniversity), default(enumSubject))
{
}
public Student(string fullname, string course, string email, string phonenr, enumUniversity university, enumSubject subject)
{
this.fullName = fullname;
this.course = course;
this.email = email;
this.phonenr = phonenr;
this.university = university;
this.subject = subject;
}