【发布时间】:2014-01-08 16:34:44
【问题描述】:
我有两个类。这是我的代码:
//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
}
}
我做错了吗?由于 Student 是 People 的子类,我希望 NAME 属性应该可以通过 Student 实例访问。非常感谢您提前提供的帮助。
【问题讨论】:
-
可以在子实例中访问。您必须将其公开才能从外部访问。你可以阅读更多关于访问修饰符here
-
我会将第一位缩短为受保护的字符串 Name {get;set;}
-
@Pierre-LucPineault 你可以把它作为答案
-
@MikeyMouse Meh 不是真的,评论就可以了,无论如何都会通知 OP。除了“使用公共并阅读文档”之外,没有什么可说的。
标签: c# polymorphism access-modifiers