gpt4 book ai didi

c# - 为什么我不能访问派生类中的 protected 属性

转载 作者:行者123 更新时间:2023-11-30 19:26:49 26 4
gpt4 key购买 nike

我有两个类。这是我的代码:

//My Base class
public class People
{
public People()
{
}

protected string name;

protected string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}

}

//The Child class

public class Student:People
{
private int id;

public Student()
{
}

public Student (int id, string name)
{
this.id = id;
this.Name = name;
}

public int ID
{
get
{
return this.id;
}

set

{
this.id = value;
}

}
}

当我像下面这样创建 Student 类的实例时,我无法从父类 People 访问 NAME 属性。

 public partial class Form1 : Form
{

private void button1_Click(object sender, EventArgs e)
{
Student student1 = new Student();
student1. // only ID property is accessible

}
}

我做错了吗?由于 Students 是 People 的子类,我希望通过 Student 实例可以访问 NAME 属性。非常感谢您提前提供的帮助。

最佳答案

你没有做错什么,但是如果你想访问

Name

通过一个实例

Student

您必须将该属性声明为public。否则,只允许从该类内部进行访问(而不是通过实例)。

关于c# - 为什么我不能访问派生类中的 protected 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com