C# 访问 protected 字段

标签 c# inheritance

这个问题在这里已经有了答案:





Is there a way to reach a `protected` member of another object from a derived type?

(7 个回答)


8年前关闭。




我想组织一个场景图。
我有通用类 SceneNode:

public class SceneNode
{
    protected SceneNode prev, next;
    protected SceneNodeContainer parent;

    public SceneNode Parent { get { return parent; } }
    public SceneNode PreviousNode { get { return prev; } }
    public SceneNode NextNode { get { return next; } }
}

我也有类 SceneNodeContainer,它是这样的:
public class SceneNodeContainer : SceneNode
{
    SceneNode firstChild, lastChild;

    public SceneNode FirstChild { get { return firstChild; } }
    public SceneNode LastChild { get { return lastChild; } }

    public void Add(SceneNode node)
    {
        Debug.Assert(node != null);
        Debug.Assert(node.parent == null);

        node.parent = this;
        node.prev = lastChild;
        node.next = null;

        if (lastChild == null)
        {
            lastChild = node;
            firstChild = lastChild;
        }
        else
        {
            lastChild.next = node;
            lastChild = node;
        }
    }

    public void Remove(SceneNode node)
    {
        Debug.Assert(node != null);
        Debug.Assert(node.parent == this);

        //unlink node
        if (node.next != null)
            node.next.prev = node.prev;

        if (node.prev != null)
            node.prev.next = node.next;

        if (node == firstChild)
            firstChild = node.next;

        if (node == lastChild)
            lastChild = node.prev;

        node.parent = null;
        node.next = null;
        node.prev = null;
    }
}

IntelliSense 表示无法从 SceneNodeContainer 访问 node.parent 和其他 protected 字段。我该如何克服呢?

最佳答案

您不能,因为 protected 工作方式 - 它只允许访问已知为子类型(或子类型)的对象的 protected 字段。所以如果 nodeSceneNodeContainer变量,您可以访问这些字段 - 但除此之外,您没有。

从 C# 4 规范的第 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.



(顺便说一句,我个人还是会避免使用 protected 字段。我几乎在所有情况下都将非常量字段设为私有(private)。)

关于C# 访问 protected 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7944252/

相关文章:

iphone - 如何在 iOS sdk 中使用继承

c++ - 当类层次结构中只有一个类时,避免在每次函数调用时读取 V 表的开销

inheritance - GORM 关系中的抽象类

c# - 从 WinService 监视剪贴板

c# - Directory.Move 子文件夹和父文件夹时 IOException 访问被拒绝

c# - 动态 LINQ 表达式

java - 抽象类和接口(interface)中相同的方法具有不同的返回类型

java - 检测隐藏的 java bean 属性

c# - 这个foreach中间有个cast,能翻译成linq吗?

c# - UWP 关闭信息亭模式