(這個問題是一個後續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 –