在 VB.NET 中标记类静态

正如最近的 有个问题回答中所述,您不能从静态类继承。如何执行与 VB.NET 中的静态类相关的规则?由于该框架兼容 C # 和 VB,因此有一种方法可以标记类静态,但似乎没有这种方法。

104798 次浏览

Module == static class

If you just want a class that you can't inherit, use a NotInheritable class; but it won't be static/Shared. You could mark all the methods, properties, and members as Shared, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler.

If you really want the VB.Net equivalent to a C# static class, use a Module. It can't be inherited and all members, properties, and methods are static/shared.

If you just want to create a class that you can't inherit, in C# you can use Sealed, and in VB.Net use NotInheritable.

The VB.Net equivalent of static is shared.

From the CLR point of view, C# static class is just "sealed" and "abstract" class. You can't create an instance, because it is abstract, and you can't inherit from it since it is sealed. The rest is just some compiler magic.

You can create static class in vb.net. The solution is

Friend NotInheritable Class DB
Public Shared AGE As Integer = 20
End Class

AGE variable is public static, you can use it in other code just like this

 Dim myage As Integer = DB.AGE

Friend = public, NotInheritable = static

Almost there. You've got to prevent instantiation, too.

NotInheritable Class MyStaticClass


''' <summary>
''' Prevent instantiation.
''' </summary>
Private Sub New()


End Sub


Public Shared Function MyMethod() As String


End Function


End Class
  • Shared is like method of static class.
  • NotInheritable is like sealed.
  • Private New is like static class can not be instantiated.

See:
MSDN - Static Classes and Static Class Members