Is there a way to set a Module to behave like a static class?
This questions is for VBers, it's irrelevant in C#.
In VB, when you create a module, all it's functions and members are available in the scope without need to type the module name, just like all the VB functions (Rnd, Mid, IIf etc.).
I want to create a module but I should have to explicitly write it's name to access it's members, i.e. it shouldn't be loaded to the开发者_运维知识库 scope like a namespace.
Update
For example, I have a Module of extension methods, I don't want all it's members to show up on the scope and in the intellisense.
I want it to be available only by instance.ExtensionMethod()
.
Any ideas?
If you create a Class instead of a Module then VB.NET will insist you use the class name. For example:
Public MustInherit Class Utils
Public Shared Function Sqr(ByVal arg As Double) As Double
Return arg * arg
End Function
End Class
...
Dim result As Double = Utils.Sqr(42) 'Utils required
It is hardly necessary, but you can prevent anyone from inheriting this class by adding a private constructor.
Update
To avoid extension methods from polluting the global namespace in IntelliSense. I found a rather unexpected workaround for this:
Imports System.Runtime.CompilerServices
Imports System.ComponentModel
<EditorBrowsable(EditorBrowsableState.Never)> _
Module Extensions
<Extension()> _
Public Sub Method(ByVal obj As ExampleClass)
End Sub
End Module
You could just add it to another namespace. I.e. if you want to call Foo.Bar and you have a module called FooModule, put it in a namespace called Foo.
Or... just have a regular class with a bunch of shared methods.
Just add a namespace around the module:
Namespace MyModule
Module MyModule
Sub MyMethod()
End Sub
End Module
End Namespace
(Oh, and I'm not a VB:er... ;) )
精彩评论