Accessing protected members in VB.NET
According to this post the following code below should compile, while it does not.
class Base
开发者_如何学C 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
What could be the problem with it? I just made a new VB.NET console project and copy-pasted the code.
The error message I get is: 'SampleProject.Base.m_x' is not accessible in this context because it is 'Protected', and I have checked on different .NET framework versions (2.0, 3.0 and 3.5).
Protected members are only accessible from derived classes via MyBase.m_x
(base in C#).
You could write:
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
- base(C#): http://msdn.microsoft.com/de-de/library/hfw7t1ce%28VS.80%29.aspx
The reason why other.m_x = 2
does not compile is, because other
is not(or must not necessarily be) the base class' instance of the current instance of Derived1. It could be any instance of Base because it is a parameter value.
You can access the inherited variable, not the one from an instance of the base class.
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
A key aspect of protected members is that a class can effectively seal off inherited protected members from access by any classes other than its ancestors (it would be nice if a class could both override a parent's method/property and also block child classes from accessing it, but so far as I can tell there's no way of doing that without adding an extra layer of hierarchy). For example, a class which happens to support cloning, but might be a useful base class for classes which would not, could have a Protected "Clone" method. Subclasses which don't support cloning could prevent their own subclasses from calling Clone by creating a dummy nested class called "Clone" which would shadow the parent Clone method.
If objects could access protected members elsewhere in the inheritance chain, this aspect of "protected" would no longer be applicable.
精彩评论