根据这个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”在此上下文中无法访问,因为它是“ protected ”,并且我已经检查了不同的 .NET 框架版本(2.0、3.0 和 3.5)。
最佳答案
protected 成员只能通过MyBase.m_x
(C# 中的基类)从派生类访问。
你可以这样写:
public sub Foo(other as Base)
MyBase.m_x = 2
end sub
- MyBase(VB.Net):http://msdn.microsoft.com/en-us/library/dzfhkk01%28VS.71%29.aspx
- 基础(C#):http://msdn.microsoft.com/de-de/library/hfw7t1ce%28VS.80%29.aspx
之所以other.m_x = 2
无法编译是因为other
不是(或者不一定是)当前实例的基类实例派生1。它可以是 Base 的任何实例,因为它是一个参数值。
关于.net - 访问 VB.NET 中 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4304442/