看看下面的例子,注意注释
public class A
{
private int x;
static void F(A a, B b)
{
a.x = 1; // Ok
b.x = 1; // Ok
}
}
public class B: A
{
static void F(A a, B b)
{
a.x = 1; // 'A.x' is inaccessible due to its protection level
b.x = 1; // 'A.x' is inaccessible due to its protection level
}
}
-------------------------------------
public class A
{
protected int x;
static void F(A a, B b)
{
a.x = 1; // Ok
b.x = 1; // Ok
}
}
public class B: A
{
static void F(A a, B b)
{
a.x = 1; // Cannot access protected member 'A.x' via a qualifier of type 'A'; the qualifier must be of type 'B' (or derived from it)
b.x = 1; // Ok
}
}
在 A 中可以通过 A 和 B 的实例访问 x,这是因为在两种情况下访问都通过 A 的实例或从 A 派生的类发生。但是在 B 中,由于 A 不从 B 派生,所以不可能通过 A 的实例访问 x。

浙公网安备 33010602011771号