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

โปรแกรม C# คืนค่าอาร์เรย์จากเมธอด


ภาพรวม

เมธอดใน C# สามารถคืนค่าอาร์เรย์ได้ โดยระบุชนิดคืนเป็น T[] และ return อาร์เรย์ที่สร้าง/เตรียมไว้

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

using System;

public class Demo
{
    public static void Main()
    {
        Console.WriteLine(string.Join(" ", Display()));
    }
    static string[] Display()
    {
        string[] str = new string[5];
        str[0] = "My"; str[1] = "name"; str[2] = "is"; str[3] = "Brad"; str[4] = "Pitt";
        return str;
    }
}

ผลลัพธ์

My name is Brad Pitt

ข้อสังเกต

  • อาร์เรย์เป็น reference type - คืน reference ไปยังอาร์เรย์เดียวกัน (ไม่ copy)
  • หากต้องการป้องกันการแก้ไขจากภายนอก ให้ return (string[])arr.Clone(); หรือ arr.ToArray()
  • สามารถคืน null ได้ - ผู้เรียกต้องตรวจสอบ
  • C# 7.0+ ใช้ expression-bodied: string[] Display() => new[] { "My", "name", "is", "Brad", "Pitt" };