在VB.NET中访问受保护的成员
根据这一点,下面的代码应该编译,而不是在VB.NET中访问受保护的成员,.net,vb.net,.net,Vb.net,根据这一点,下面的代码应该编译,而不是 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
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 framework版本(2.0、3.0和3.5)。您可以访问继承的变量,而不是从基类实例访问的变量
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
受保护的成员只能通过
MyBase.mx
(以C#为基)从派生类访问。
你可以写:
public sub Foo(other as Base)
MyBase.m_x = 2
end sub
- MyBase(VB.Net):
- 基础(C#):
other.m_x=2
未编译的原因是,因为other
不是(或不一定是)Derived1当前实例的基类实例。它可以是Base的任何实例,因为它是一个参数值。受保护成员的一个关键方面是,类可以有效地阻止继承的受保护成员被其祖先以外的任何类访问(如果一个类既可以重写父类的方法/属性,又可以阻止子类访问它,那就太好了,但就我所知,如果不添加额外的层次结构,就无法做到这一点)。例如,一个碰巧支持克隆但可能是不支持克隆的类的有用基类的类可以有一个受保护的“Clone”方法。不支持克隆的子类可以通过创建一个名为“Clone”的伪嵌套类来阻止自己的子类调用克隆,该类将隐藏父克隆方法
如果对象可以访问继承链中其他位置的受保护成员,“受保护”的这一方面将不再适用。这在技术上是不正确的。如果两者都是
Derived1
类型,您可以访问两者的受保护成员。问题是他使用的是不合法的基类型(因为other
可能类似于Derived42
,它与Derived1
没有任何关系)。@Justin-澄清我说的是基类的一个实例。将Foo()移动到基类。