What is the use of a shared variable in VB.NET?

2020-01-26 09:59发布

What is the use of a Shared variable in VB.NET?

标签: vb.net
3条回答
再贱就再见
2楼-- · 2020-01-26 10:21

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.

Public Class MyClass
    Public Sub MyMethod()
        ' Do something in the method
    End Sub
End Class

In order to call that method you would need an instance of the class in order to call the method. Something like:

Dim myvar As MyClass = New MyClass()
myvar.MyMethod()

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.

Public Class MyClass
    Public Shared Sub MyMethod()
        ' Do something in the method
    End Sub
End Class

And then:

MyClass.MyMethod()

You can also see examples of this in the .NET framework itself. For example, the "string" type has many static/shared methods. I.e.

' Using an instance method (i.e. Non-shared) of the string type/class.
Dim s As String = "hello"
s.Replace("h", "j")

' Using a static/shared method of the string type/class.
s = String.Concat(s, " there!");

Here's a good article that explains it further:

Shared Members and Instance Members in VB.NET

查看更多
地球回转人心会变
3楼-- · 2020-01-26 10:28

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.

MyClass.DoSomething()

rather than

Dim oObject as New MyClass()
oObject.DoSomething()
查看更多
地球回转人心会变
4楼-- · 2020-01-26 10:36

Simply whenever you want to have single instance of variable for entire application, shared between objects of your class. Instead of 1-per-object.

查看更多
登录 后发表回答