gpt4 book ai didi

c# - 如果 sibling 不能,为什么 parent 可以访问子类的 protected 成员的实例?

转载 作者:太空狗 更新时间:2023-10-29 21:17:09 24 4
gpt4 key购买 nike

this question 中所述, 和 these articles , 以下是不允许的:

public class A
{
protected virtual int X {get; private set;}
}

public class B : A
{
public int Add(A other)
{
return X + other.X;
}
}

因为如果它是,而且你有这个:

public class C : A 
{
protected override int X { get { return 4; } }
}

然后:

A c = new C();
B b = new B();
b.Add(c);

这是非法的,因为即使 B 访问 X 意味着它知道 C 具有所需的签名 仍然不允许实际访问该成员。


到目前为止,还不错。但是考虑到上述情况,我感到困惑的是为什么我可以这样做:

public class A
{
protected virtual int X { get; private set; }

public int Add(A other)
{
return X + other.X;
}
}

因此,这:

A c = new C();
A a = new A();
a.Add(c);

definition of the protected keyword说:

A protected member is accessible within its class and by derived class instances.

但现在 C 上的 protected 成员正在从 A 中访问,它既不是“它的类”也不是“派生类实例”,而是一个 类。虽然 A 显然可以访问 signature,但同级示例似乎表明仅此一项还不够,那么为什么 protected授予它对成员的访问权限?

最佳答案

这由 the specification 定义:

When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access is required to take place through an instance of the derived class type in which the access occurs.:

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; // Error, must access through instance of B
b.x = 1; // Ok
}
}

within A, it is possible to access x through instances of both A and B, since in either case the access takes place through an instance of A or a class derived from A. However, within B, it is not possible to access x through an instance of A, since A does not derive from B.

这就是我不希望类 C 的任何人访问我的“内部”,尽管允许派生 self 的类 A state 在类 B 中,尽管它们都有一个事实,即它们都是类 A 的派生类。

关于c# - 如果 sibling 不能,为什么 parent 可以访问子类的 protected 成员的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29988135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com