函数内部的C#struct数组

时间:2016-11-22 10:57:06

标签: c# function struct

我正在尝试结构,我无法弄清楚如何在函数内部使用它们。 稍后,我需要开发一段代码,允许我添加学生并重新输入一些细节。

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);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

代码中唯一的问题是,当您的代码不在范围内时,您正试图访问arr

您已在arr方法中声明Main,这意味着它只能在那里访问。如果你把它声明为你班上的一个字段,那么你就可以访问它,一切都会按预期工作。或者,您可以将数组作为参数传递给使用它的方法,并以这种方式访问​​它。

简而言之:问题与结构无关,它与变量的范围有关,你会遇到与类相似的问题。

另外需要注意的是:当我编译你的代码时(并且为了提供易于编译的代码示例而做得很好)我得到了错误,例如:

  

错误CS0103:当前上下文中不存在名称“arr”

并且会包含确切的行号,并且应该告诉您如何修复错误。