Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เทียบเท่า VB Module ใน C#: Static Class

ภาพรวม

VB.NET Module คล้ายกับ static class ใน C# - สมาชิกทั้งหมดเป็น Static เข้าถึงได้โดยไม่ต้องสร้าง Instance

การเปรียบเทียบ

VB.NET Module


Module MyModule
    Public Sub Display()
        MsgBox("Demo!")
    End Sub

    Public Property Counter As Integer = 0
End Module

' ใช้งาน
MyModule.Display()
MyModule.Counter = 5

C# Static Class


using System;

public static class MyModule {
    public static void Display() {
        Console.WriteLine("Demo!");
    }

    public static int Counter { get; set; } = 0;
}

// ใช้งาน
MyModule.Display();
MyModule.Counter = 5;

คุณสมบัติของ Static Class

  • ไม่สามารถสร้าง Instance ได้ (new MyModule() ❌)
  • สมาชิกทุกตัวต้องเป็น static
  • ไม่สามารถ Implement Interface ได้
  • ไม่สามารถ Inherit ได้ (Implicitly Sealed)
  • มี Static Constructor เดียว (Parameterless, เรียกก่อนการใช้งานครั้งแรก)

Static Constructor


public static class Config {
    public static string ConnectionString { get; private set; }
    public static int MaxRetries { get; private set; }

    // Static Constructor - เรียกอัตโนมัติครั้งแรกที่เข้าถึง class
    static Config() {
        ConnectionString = LoadConnectionString();
        MaxRetries = 3;
        Console.WriteLine("Config initialized");
    }

    static string LoadConnectionString() => "Server=...";
}

Extension Methods (ต้องอยู่ใน Static Class)


public static class StringExtensions {
    public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s);

    public static string Truncate(this string s, int maxLength) {
        if (string.IsNullOrEmpty(s) || s.Length <= maxLength) return s;
        return s.Substring(0, maxLength) + "...";
    }
}

// ใช้งาน
string s = "Hello World";
Console.WriteLine(s.Truncate(5)); // Hello...

เมื่อไหร่ใช้ Static Class vs Singleton

Static ClassSingleton
Utility/Helper Methods (Stateless)Stateful Service (มี State)
Extension MethodsLazy Initialization ต้องการ
Constants/ConfigurationInterface Implementation ต้องการ
ไม่ต้องการ Dependency Injectionต้องการ DI / Mocking ใน Test

Best Practices

  • ใช้สำหรับ Pure Functions, Utilities, Constants
  • หลีกเลี่ยง Shared Mutable State ใน Static Class (Thread Safety Issues)
  • ถ้าต้องการ State ให้ใช้ Singleton หรือ Dependency Injection แทน
  • Static Constructor ใช้สำหรับ One-time Initialization