What is the use of a Shared
variable in VB.NET?
相关问题
- 'System.Threading.ThreadAbortException' in
- how to use special characters like '<'
- C# to VB - How do I convert this anonymous method
- Scaling image for printing
- visual basics equal to or greater than
相关文章
- vb.net 关于xps文件操作问题
- Checking for DBNull throws a StrongTypingException
- Using the typical get set properties in C#… with p
- Load a .NET assembly from the application's re
- C# equivalent of VB DLL function declaration (Inte
- What other neat tricks does the SpecialNameAttribu
- Automatically install updates with ClickOnce deplo
- Resetting Experimental instance of Visual Studio
The "Shared" keyword in VB.NET is the equivalent of the "static" keyword in C#.
In VB.NET, the Shared keyword can be applied to Dim, Event, Function, Operator, Property, and Sub statements within a class; however, in C#, the
static
keyword can be applied both to these statements within a normal class, and also at the class level to make the entire class static.A "Shared" or "static" method acts upon the "type" (that is, the class) rather than acting upon an instance of the type/class. Since
Shared
methods (or variables) act upon the type rather than an instance, there can only ever be one "copy" of the variable or method as opposed to many copies (one for each instance) in the case of non-shared (i.e., instance) methods or variables.For example: If you have a class, let's call it MyClass with a single non-shared method called MyMethod.
In order to call that method you would need an instance of the class in order to call the method. Something like:
If this method was then made into a "shared" method (by adding the "Shared" qualifier on the method definition, you no longer need an instance of the class to call the method.
And then:
You can also see examples of this in the .NET framework itself. For example, the "string" type has many static/shared methods. I.e.
Here's a good article that explains it further:
Shared Members and Instance Members in VB.NET
It is the same as
static
in C# and most other languages. It means that every object in the class uses the same copy of the variable, property or method. When used with a method as it is static you don't need an object instance.rather than
Simply whenever you want to have single instance of variable for entire application, shared between objects of your class. Instead of 1-per-object.