(这个问题是一个后续C# accessing protected member in derived class)C#保护字段访问
我有下面的代码片段:
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
源自Fox
,所以编译器知道它有权访问相应的受保护字段。另外,正如您在
CorrectPaintFox
中看到的那样,我可以访问RedFox
类实例的受保护字段。 那么,为什么我不能期望从Fox
类实例相同?
有一个[Eric Lippert关于该主题的博客文章](http://blogs.msdn.com/b/ericlippert/archive/2005/11/09/491031.aspx)。 –
为什么?因为这是指定语言的方式:http://msdn.microsoft。com/en-us/library/aa691129(v = vs.71).aspx –