ผู้รับมอบสิทธิ์ C # (เอาต์พุตไม่แสดงค่าที่ถูกต้อง)

ฉันกำลังพยายามรับผลลัพธ์เป็น "1111111111" ฟังก์ชันข้อความถูกเรียกโดย AddMessage และจะเก็บข้อความไว้ในอาร์เรย์ อย่างไรก็ตาม เมื่อฉันส่งออกค่าอาร์เรย์ ฉันจะได้รับที่อยู่แทนค่า ฉันจะแก้ไขสิ่งนี้ได้อย่างไร?

class Program
{
    public delegate int print();

    public static void Main()
    {
        print[] array1 = new print[10];

        AddMessage(ref array1, Message);

        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(array1[i]);
        }
    }


    public static void AddMessage(ref print[] array, print msg)
    {
        for(int i =0; i< 10; i++)
        {
            array[i] = msg;
        }
    }

    public static int Message()
    {
        int msg;
        msg = 1;
        return msg;
    }


} 

}


person JeremyM    schedule 01.11.2017    source แหล่งที่มา
comment
ในโค้ดของคุณ ไม่จำเป็นต้องใช้ ref ใน ref print[] array - แค่ print[] array ก็เพียงพอแล้ว ทำไมคุณถึงใส่ ref?   -  person Enigmativity    schedule 01.11.2017


คำตอบ (2)


ผู้รับมอบสิทธิ์คือฟังก์ชัน คุณกำลังส่งการอ้างอิงไปยังฟังก์ชันนั้นเอง (ไม่ใช่ผลลัพธ์) ไปยัง Console.WriteLine

Console.WriteLine(array1[i]);

จะต้องกลายเป็น

Console.WriteLine(array1[i]());
person caesay    schedule 01.11.2017

คุณกำลังพิมพ์ชื่อวัตถุเนื่องจากคุณไม่ได้โทรหาผู้รับมอบสิทธิ์:

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(array1[i]);
}

คุณควรเปลี่ยนสิ่งนี้เป็น array1[i]()

person Llama    schedule 01.11.2017
comment
ขอบคุณ ฉันเข้าใจแล้ว. - person JeremyM; 01.11.2017