【问题标题】:Accessing protected members in VB.NET在 VB.NET 中访问受保护的成员
【发布时间】:2010-11-29 13:58:31
【问题描述】:

根据post,下面的代码应该可以编译,但它没有。

class Base
    protected m_x as integer
end class

class Derived1
    inherits Base
    public sub Foo(other as Base)
        other.m_x = 2
    end sub
end class

class Derived2
    inherits Base
end class

它可能有什么问题?我刚刚创建了一个新的 VB.NET 控制台项目并复制粘贴了代码。

我收到的错误消息是:在此上下文中无法访问“SampleProject.Base.m_x”,因为它处于“受保护”状态,并且我检查了不同的 .NET 框架版本(2.0、3.0 和 3.5)。

【问题讨论】:

  • 将 Foo() 移至基类。

标签: .net vb.net


【解决方案1】:

受保护的成员只能通过MyBase.m_x(C# 中的基础)从派生类中访问。 你可以写:

public sub Foo(other as Base)
    MyBase.m_x = 2
end sub

other.m_x = 2 无法编译的原因是,other 不是(或不一定是)Derived1 当前实例的基类实例。它可以是 Base 的任何实例,因为它是一个参数值。

【讨论】:

    【解决方案2】:

    您可以访问 inherited 变量,而不是来自基类的 实例 的变量。

    class Base
        protected m_x as integer
    end class
    
    class Derived1
        inherits Base
        public sub Foo(other as Base)
            MyBase.m_x = 2 ' OK - Access inherited member
            other.m_x = 2 ' NOT OK - attempt to access a protected field from another instance
        end sub
    end class
    

    【讨论】:

    • 这在技术上是不正确的。如果两者都是Derived1 类型,您可以访问两者的受保护成员。问题是他使用了不合法的基本类型(因为other 可能类似于Derived42,与Derived1 没有关系)。
    • @Justin - 澄清我说的是基类的一个实例。
    【解决方案3】:

    受保护成员的一个关键方面是,一个类可以有效地隔离继承的受保护成员,使其不被其祖先以外的任何类访问(如果一个类既可以覆盖父类的方法/属性,又可以阻止子类)从访问它,但据我所知,如果不添加额外的层次结构,就无法做到这一点)。例如,一个恰好支持克隆的类,但对于不支持克隆的类可能是一个有用的基类,它可能具有受保护的“克隆”方法。不支持克隆的子类可以通过创建一个名为“Clone”的虚拟嵌套类来阻止它们自己的子类调用 Clone,这会影响父 Clone 方法。

    如果对象可以访问继承链中其他位置的受保护成员,则“受保护”的这一方面将不再适用。

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 2016-10-01
      • 2013-08-06
      • 2015-01-30
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多