gpt4 book ai didi

c# - 无法访问同一基类的 protected 成员

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:36 24 4
gpt4 key购买 nike

我有这样的东西:

class Node
{
protected Node Parent
{
get; private set;
}
}

class NodeDerived : Node
{
void SomeMethod()
{
Node parentIterator = this.Parent;

while (parentIterator != null)
{
// ... some logic

parentIterator = parentIterator.Parent; // Here's the error
}
}
}

但是由于某些奇怪的原因,我无法访问 parentIterator.Parent 属性:

error CS1540: Cannot access protected member `Node.Parent' via a qualifier of type `Node'. The qualifier must be of type `NodeChild' or derived from it

为什么会这样?顺便说一句,我还发现虽然我可以访问this.Parent,但我无法访问((Node) this).Parent

最佳答案

来自 C# 5 规范,第 3.5.3 节:

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 must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

因此您可以访问任何 NodeDerived 对象的 Parent 属性:

NodeDerived derivedNode = ...;
Node parent = derivedNode.Parent;

...但是您不能访问不是 NodeDerived 或子类的节点类型的 Parent 属性。

使用 this.Parent 是可行的,因为 this 的编译时类型是 NodeDerived

我怀疑您想要公开您的 Parent 属性 - 假设您希望此代码与 NodeDerived 以外的节点一起使用。

关于c# - 无法访问同一基类的 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21457268/

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