C# 在 VB.NET 中标记静态类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/135841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Marking A Class Static in VB.NET
提问by MagicKat
As just stated in a recent questionand answer, you can't inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.
正如最近刚提及的问题和答案,你不能从一个静态的类继承。如何强制执行与 VB.NET 中的静态类一起使用的规则?由于该框架在 C# 和 VB 之间兼容,因此有一种方法可以将类标记为静态,但似乎没有办法。
采纳答案by Joel Coehoorn
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.
如果你只是想要一个你不能继承的NotInheritable
类,就使用一个类;但它不会是静态/共享的。您可以将所有方法、属性和成员标记为Shared
,但这与 C# 中的静态类并不严格相同,因为它不是由编译器强制执行的。
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.
如果您真的希望 VB.Net 等效于 C# 静态类,请使用Module
. 它不能被继承,所有成员、属性和方法都是静态/共享的。
回答by Charles Graham
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.
如果只想创建一个不能继承的类,在C#中可以使用Sealed,在VB.Net中使用NotInheritable。
The VB.Net equivalent of static is shared.
VB.Net 等效于 static 是共享的。
回答by Ilya Ryzhenkov
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.
从 CLR 的角度来看,C# 静态类只是“密封”和“抽象”类。你不能创建一个实例,因为它是抽象的,你不能继承它,因为它是密封的。其余的只是一些编译器魔术。
回答by Mentor
You can create static class in vb.net. The solution is
您可以在 vb.net 中创建静态类。解决办法是
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
AGE 变量是公共静态的,你可以像这样在其他代码中使用它
Dim myage As Integer = DB.AGE
Friend = public, NotInheritable = static
朋友 = 公共,NotInheritable = 静态
回答by Gary Newsom
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.
- 共享就像静态类的方法。
- NotInheritable 就像密封的一样。
- Private New 就像不能实例化的静态类。
See:
MSDN - Static Classes and Static Class Members
请参阅:
MSDN - 静态类和静态类成员