且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在VB.NET中使用模块是否被认为是不好的做法?

更新时间:2022-11-16 12:51:04

Centro 正确的是,模块(或具有共享成员的NotInheritable类)是 最近等效于C#静态类.因此,从技术上讲,这没有什么错,因为它只是VB创建此类的一种方法.例如,您不能在VB中说Public Shared Class Settings,因为您不能将Shared关键字放在类上.

Centro is right that a Module (or a NotInheritable Class with Shared members) is the closest equivalent to a C# static class. So technically, nothing is wrong with it as it's just one of VB's ways of creating this type of class. For example, you cannot say Public Shared Class Settings in VB as you cannot put the Shared keyword on a class.

如果在特定情况下需要使用Module,那么我不会将其称为坏习惯,但是对于松散耦合,可测试的代码,您可能不希望使用Module(或其他静态类等效项)作为设计选择.此外,尽管具有共享成员的NotInheritable类比仅说模块具有更多的描述性,但在至少一种情况下,必须使用模块代替.

On its own I wouldn't call it bad practice if a specific circumstance calls for a Module, but otherwise a Module (or other static class equivalents) likely is not the design choice you want for having loosely coupled, testable code. Additionally, while a NotInheritable Class with Shared members is more descriptive than just saying Module, there is at least one circumstance where a Module must be used instead.

何时需要在VB.Net中使用模块?如果您想利用扩展方法,那么这是您唯一的选项,因为如上所述,您不能在VB.Net中创建共享(静态)类,也不能在NotInheritable Classes上使用扩展名.您必须使用以下模块:

When would you need to use Modules in VB.Net? If you want to take advantage of extension methods, then it's your only option since as mentioned, you cannot create a shared (static) class in VB.Net, neither can you use extensions on NotInheritable Classes. You must use a module as follows:

Imports System.Runtime.CompilerServices

Public Module StringExtensions
    <Extension()> _
    Public Function Remove( _
                        ByVal input As String, _
                        ByVal subStrings As String()) As String
        Return String.Join("", input.Split(subStrings, StringSplitOptions.None)).Trim()
    End Function
End Module

在C#中,您不能使用模块,而必须使用静态类,如下所示:

In C# you can't use modules and must use static classes as follows:

public static class StringExtensions
{
    public string Remove(this string input, string[] subStrings)
    {
        return string.Join("", input.Split(subStrings, StringSplitOptions.None)).Trim();
    }
}