Is there a way to make a constructor for a shared
class in VB.NET? I do it all the time in C# as follows, but I can't seem to get it to work in VB.NET.
static class someClass
{
public static string somePublicMember;
static someClass()
{
messageBox.show("I just constructed a static class");
}
}
When the following code is executed, the constructor will be called.
...
someSillyClass.someSillyPublicMember = 42;
...
Can a static
( shared
) class even have a constructor in VB.NET?
Read documentation here . In you can do
Shared Sub New()
...
End Sub
And it will be invoked. From MSDN:
Shared constructors are run before any instance of a class type is created.
Shared constructors are run before any instance members of a structure type are accessed, or before any constructor of a structure type is explicitly called. Calling the implicit parameter less constructor created for structures will not cause the shared constructor to run.
Shared constructors are run before any of the type's shared members are referenced.
Shared constructors are run before any types that derive from the type are loaded.
A shared constructor will not be run more than once during a single execution of a program.
Kind of looks like a normal constructor in VB.NET:
Shared Sub New()
End Sub
Have you tried:
Class someClass
Public Shared somePublicMember As String
Shared Sub New()
messageBox.show("I just constructed a static class")
End Sub
End Class
There are no static/shared classes in VB.net.
There are however Modules that provide similar, thus you will not be able to instantiate them.
Your equivalent code in VB.Net would be (tested using VS2017):
Module someClass
Public somePublicMember As String
Sub New()
messageBox.show("I just constructed a static class (not really) [sic]")
End Sub
End Module
You cannot declare a shared class in VB.NET. You have two options:
Init
, which you need to call before anything else.
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.