C#初学者求助:构造函数因访问级别问题无法访问
实例化Student类时出现“保护级别导致无法访问”错误的解决办法
错误原因
你的Student类构造函数被标记为private:
private Student(String Name, int StudentId, double GPA)
在C#中,private修饰的成员仅能在当前类内部访问,而你在Main方法(属于另一个类,比如默认的Program类)中尝试调用这个构造函数创建实例,自然会触发“无法访问”的错误。
解决方法
将Student类的构造函数访问修饰符改为public,允许外部代码调用它来实例化对象:
public Student(String Name, int StudentId, double GPA)
修正后的完整代码
static void Main(string[] args) { Student Student1 = new Student("Aya", 00001, 4.0); Console.WriteLine(Student1.getName()); Student1.setGPA(3.5); Console.WriteLine(Student1.getGPA()); } public class Student { private String Name; private int StudentId; private double GPA; // 修改为public构造函数 public Student(String Name, int StudentId, double GPA) { this.Name = Name; this.StudentId = StudentId; this.GPA = GPA; } public String getName() { return this.Name; } public int getStudentId() { return this.StudentId; } public double getGPA() { return this.GPA; } public void setGPA(double GPA) { this.GPA = GPA; } }
内容的提问来源于stack exchange,提问作者Aya Abdat
相关产品推荐
相关产品推荐

