VB.NET中的静态方法实现 [英] Static Method implementation in VB.NET

查看:45
本文介绍了VB.NET中的静态方法实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对VB.NET中的 Static 实现感到困惑.在C#中,我们可以创建Static类和static方法来为我们的应用程序编写实用程序方法.

I am confused with Static implementation in VB.NET. In C#, we can create Static class and static methods to write utility methods for our application.

现在,VB.NET允许我们创建 Module 代替静态类.如果我们在模块中创建方法,则默认情况下它将变为静态.但是在我的应用程序中,我编写了以下代码:

Now, VB.NET lets us create Module in place of static class. If we create a method in the module, by default it becomes static. But in my application, I have written the below code:

Public Class Utility
    Public Shared Function GetValue() As String
       // My code
    End Function
End Class

通过编写代码,我可以使用 Utility.GetValue()访问实用程序方法.由于这不是静态类,因此我应该实例化它的一个对象.但是此方法可用于 Utility

By writing the code, I am able to access the utility method as Utility.GetValue(). As this is not a static class, I am supposed to instantiate an object of it. But this method is available for both the class and objects of Utility

现在我的问题是:

  1. 我执行的实现是否可能违反了模块提供的静态类的任何功能?
  2. 这和实现模块之间有什么区别?
  3. 如果我改为创建一个模块,该模块的范围将与此类相同吗?我想在整个项目以及引用该项目的其他项目中访问该方法.

我尝试查阅多篇文章,但没有一个地方能找到确切的答案.请帮忙.

I tried consulting multiple articles, but nowhere found this exact answers. Please help.

推荐答案

VB.NET模块静态类.编译器会为您处理.上面的每个方法和属性都是 static ( Shared ).

A VB.NET module is a static class. The compiler handles this for you. Every method and property on it is static (Shared).

具有静态(共享)成员的类就是这样:具有静态(共享)成员的类.您无需创建其实例即可访问静态(共享)方法,但必须获取其任何实例成员.

A class with a static (Shared) member on it is exactly that: a class with a static (Shared) member. You don't have to create an instance of it to access the static (Shared) method, but you do to get to any of its instance members.

您还可以在模块中定义 Sub New(),它成为模块的静态构造函数.第一次尝试在模块上调用成员时,将调用静态构造函数以初始化静态类.

You can also define a Sub New() in a module, and it becomes the static constructor for the module. The first time you try to invoke a member on the module, the static constructor will be invoked to initialize the static class.

这篇关于VB.NET中的静态方法实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆