【发布时间】:2012-05-26 09:49:06
【问题描述】:
(这个问题是C# accessing protected member in derived class的后续问题)
我有以下代码sn-p:
public class Fox
{
protected string FurColor;
private string furType;
public void PaintFox(Fox anotherFox)
{
anotherFox.FurColor = "Hey!";
anotherFox.furType = "Hey!";
}
}
public class RedFox : Fox
{
public void IncorrectPaintFox(Fox anotherFox)
{
// This one is inaccessible here and results in a compilation error.
anotherFox.FurColor = "Hey!";
}
public void CorrectPaintFox(RedFox anotherFox)
{
// This is perfectly valid.
anotherFox.FurColor = "Hey!";
}
}
现在,我们知道private and protected fields are private and protected for type, not instance.
我们也知道访问修饰符应该在编译时起作用。
那么,问题来了 - 为什么我不能访问
RedFox中Fox类实例的FurColor字段?RedFox派生自@ 987654330@,因此编译器知道它可以访问相应的受保护字段。另外,正如您在
CorrectPaintFox中看到的,我可以访问RedFox类实例的受保护字段。 那么,为什么我不能对Fox类实例有同样的期望呢?
【问题讨论】:
-
为什么?因为这是指定语言的方式:msdn.microsoft.com/en-us/library/aa691129(v=vs.71).aspx
标签: c# private encapsulation protected