是否可以从私有类访问受保护的变量。是的会发生什么以及它是如何运作的?
private class classname{
protected int variable_name = 5;
private void method_name(){
response.write(variable_name);
}
}
在我的采访中提到了这个问题
答案 0 :(得分:2)
是的,这是可能的,它意味着与正常情况完全相同:
public class Container
{
private class Foo
{
protected int field;
private class FurtherNested
{
// Valid: a nested class has access to all the members
// of its containing class
void CheckAccess(Foo foo)
{
int x = foo.field;
}
}
}
private class Bar : Foo
{
void CheckAccess(Foo foo)
{
// Invalid - access to a protected member
// must be through a reference of the accessing
// type (or one derived from it). See
// https://msdn.microsoft.com/en-us/library/bcd5672a.aspx
int x = foo.field;
}
void CheckAccess(Bar bar)
{
// Valid
int x = bar.field;
}
}
private class Baz
{
void CheckAccess(Foo foo)
{
// Invalid: this code isn't even in a class derived
// from Foo
int x = foo.field;
}
}
}
也就是说,从私有(因此嵌套)类型派生任何类型是相对不寻常的。