Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Tương đương VB Module trong C#

VB.NET Module = static class trong C#. Chứa phương thức/biến static, không cần instance, truy cập toàn cục.

So sánh

VB.NET Module

Module MyModule
    Public Sub Display()
        MsgBox("Demo!")
    End Sub
    
    Public Property Counter As Integer = 0
End Module

' Gọi: MyModule.Display()

C# Static Class

public static class MyModule
{
    public static void Display()
    {
        Console.WriteLine("Demo!");
    }
    
    public static int Counter { get; set; } = 0;
}

// Gọi: MyModule.Display();

Đặc điểm Static Class

  • Chỉ chứa thành viên static
  • Không thể khởi tạo (new MyModule() lỗi compile)
  • Không thể kế thừa
  • Sealed ngầm hiểu
  • Constructor static (nếu cần) chạy 1 lần trước truy cập đầu tiên

Ví dụ thực tế: Extension Methods

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string str)
        => string.IsNullOrEmpty(str);
    
    public static string Truncate(this string str, int maxLength)
        => str.Length <= maxLength ? str : str[..maxLength] + "...";
}

// Sử dụng
string s = "Hello World";
Console.WriteLine(s.Truncate(5)); // "Hello..."

Lưu ý: C# không có từ khóa module. Dùng static class cho utility/helper methods, extension methods, constants.