简体   繁体   中英

Can I use MyBase in a shared method

I have a class that inherits from a base class (this contains a lot of common db related stuff amongst other things and is marked as MustInherit). I want to write a shared method in which I call a base class method, however the compiler gives me the message 'MyBase is only valid within an instance method'. This shared method is a logging method and will be used a lot within the app, I'm trying to avoid having to instantiate an object each time I want to call it.

Is it possible to access the base class methods from a shared method?

No, as the compiler states you cannot call an instance method from a shared method.

Since an instance of a class is separate from any other instance each call to a method on that instance can potentially create different results and side-effects as an instance method has access to the instance's state . A shared method does not have access to the state of any instance since the shared method is shared between all instance of the type.

Since this is the case it is impossible to call an instance method from a shared method because a shared method is "instance-less".

Well since a shared method does not have state, calling a instance method is not possible in the sence you a re thinking, but dont dispair there is always a shared instantiated instance at the field level that your shared method can reference, in your case maby a private class that inherits from your base

something like

Public Class Foo
private Shared ReadOnly Instance as New Somthing

Public Shared Function DooFoo as string
   return instance.Getstring()
End Function

Private class Something : inherits baseclass
   public function Getstring() as string
    ....
   End function 
End Class



End Class

You actually don't need to, since you cannot have shared overridable methods in VB. You just need to specify base class like this:

Class B

    Public Shared Sub Foo()
      ' code
    End Sub

End Class

Class D : Inherits B

    Public Shared Sub Bar()
        B.Foo() ' calls base class method
    End Sub

End Class

您可能想看看使用注册表模式

Is the method you want to access in the base class a shared method? If so, just make the method protected, and in your sub class, call it without the MyBase keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM