开发者

Shared variables among subclasses

I have a problem with inherited classes. Have a look at the following VB.NET 2.0 / VS 2005 code:

MustInherit Class templateclass
    Public Shared x As String
End Class

Class child1
    Inherits templateclass
End Class

Class child2
    Inherits templateclass
End Class

The templateclass has a shared variable x which is of course inherited by the child classes. But I wonder that 开发者_如何转开发all child classes share only one x! Until now I thought that shared variables are only shared among the instances of a class, not among all childs. This is very annoying because I have a base class which I need in two slightly different versions and they should not "share the shared" variables. And because the classes have a lot of shared variables, shadowing each in the childs would be very... inelegant and cause a lot of work. Has anyone a better solution for this problem?

Thanks in advance,

Sagi


You could wrap the shared state in a dedicated class (as non-shared members), and give each of the child classes a shared member of that class. If you need to access shared state through an instance, you can implement a property that both child classes inherit, returning the shared state of the particular subclass. Note, however, that this property cannot be shared itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜