簡體   English   中英

函數內部的C#結構數組

[英]C# struct array inside a function

我正在嘗試結構,但無法弄清楚如何在函數內部使用它們。 稍后,我需要開發一段代碼,使我可以添加學生並重新輸入一些細節。

namespace struct_example
{
    struct student
    {
        public int s_id;
        public String s_name, c_name, s_dob;
    }

    class Program
    {
        static void Main(string[] args)
        {
            student[] arr = new student[4];

            for (int i = 0; i < 4; i++)
            {
                fillplz(i);
            }
            for (int i = 0; i < 4; i++)
            {
                showplz(i);
            }
            Console.ReadKey();
        }
        static void fillplz(int id)
        {
            Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
            arr[id].s_id = Int32.Parse(Console.ReadLine());
            arr[id].s_name = Console.ReadLine();
            arr[id].c_name = Console.ReadLine();
            arr[id].s_dob = Console.ReadLine();
        }
        static void showplz(int id)
        {
            Console.WriteLine(arr[id].s_id);
            Console.WriteLine(arr[id].s_name);
            Console.WriteLine(arr[id].c_name);
            Console.WriteLine(arr[id].s_dob);
        }
    }
}

代碼中的唯一問題是,當它不在范圍內時,您將嘗試訪問arr

您已經在Main方法中聲明了arr ,這意味着只能在其中訪問它。 如果您在班級中將其聲明為字段,則可以訪問它,並且一切都會按預期進行。 或者,您可以將數組作為參數傳遞給使用它的方法,然后以這種方式訪問​​它。

簡而言之:問題與結構無關,與范圍定義變量有關,並且您在類中也會遇到類似的問題。

補充說明:編譯代碼時(為提供易於編譯的代碼示例做得很好),我遇到了以下錯誤:

錯誤CS0103:名稱“ arr”在當前上下文中不存在

並且應該包括確切的行號,並且應該已經告訴您確切的錯誤修復方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM