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

โปรแกรม C# สร้างอาร์เรย์สตริงว่าง


ภาพรวม

สร้างอาร์เรย์สตริงว่าง (empty string array) ด้วย new string[0] หรือ new string[] { } หรือ Array.Empty<string>() (.NET 4.6+)

รูปแบบการใช้งาน

string[] empty1 = new string[0];
string[] empty2 = new string[] { };
string[] empty3 = Array.Empty(); // แนะนำ - singleton pattern ประหยัดหน่วยความจำ

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        string[] str = new string[] { };
        Console.WriteLine("String Array elements won't get displayed since it's empty...");
        for (int i = 0; i < str.Length; i++)
        {
            string res = str[i];
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์

String Array elements won't get displayed since it's empty...

แนวทางปฏิบัติที่ดี

  • ใช้ Array.Empty<T>() สำหรับคืนค่าอาร์เรย์ว่าง - คืน instance เดียวกันเสมอ (singleton) ประหยัด GC pressure
  • หลีกเลี่ยง new string[0] ใน hot path ที่เรียกบ่อย
  • ตรวจสอบว่าง: if (arr.Length == 0) หรือ if (!arr.Any()) (LINQ)