Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用方法初始化_C#_Initialization - Fatal编程技术网

C# 使用方法初始化

C# 使用方法初始化,c#,initialization,C#,Initialization,所以直到最近,我一直在初始化主函数中的所有内容,但这使得它(imo)非常难看。因此,我继续思考,不需要我写初始化,我只需要有一个方法来为我做这件事,它只需要通过它的名称(Create.classification())来解释它本身。因此,我继续学习,用这种方法制作了这门课: class Create { public static void ClassRoom() { Student Henry = new Student("Henry", 20);

所以直到最近,我一直在初始化主函数中的所有内容,但这使得它(imo)非常难看。因此,我继续思考,不需要我写初始化,我只需要有一个方法来为我做这件事,它只需要通过它的名称(Create.classification())来解释它本身。因此,我继续学习,用这种方法制作了这门课:

class Create
{
    public static void ClassRoom()
    {
        Student Henry = new Student("Henry", 20);
        Student Jeff = new Student("Jeff", 18);
        Student Jessica = new Student("Jessica", 22);

        Teacher MrLopez = new Teacher("Lopez", "Math", 37);
    }
这将使main看起来更漂亮:

class Program
{
    static void Main(string[] args)
    {
        Create.ClassRoom();

        Console.WriteLine(Henry.age);
    }
}

然而,它说亨利在当前的环境中并不存在。现在我明白这与范围有关,但我似乎无法思考或找到解决方案。是我的想法行不通还是我遗漏了什么?我希望它是这样,在我创建之后;它将允许我与其中初始化的任何东西进行交互

main()无法访问Henry,因为它在函数教室()的范围内。您需要让它返回一个Student对象,或者更好的做法是,创建一个类,该类包含要访问的变量的getter和setter。

是的,您是对的。这与范围有关。初始化的变量在create教室()方法之外不可访问。您必须将教室的实例返回给调用方法

按如下方式重构类:

class ClassRoom
{
    public List<Student> Students { get; private set; }
    public List<Teacher> Teachers { get; private set; }

    public ClassRoom()
    {
        this.Students = new List<Student>();
        this.Teachers = new List<Teacher>();
    }
}

class Create
{
    public static ClassRoom ClassRoom()
    {
        ClassRoom classRoom = new ClassRoom();
        classRoom.Students.Add(new Student("Henry", 20));
        classRoom.Students.Add(new Student("Jeff", 18));
        classRoom.Students.Add(new Student("Jessica", 22));

        classRoom.Teachers.Add(new Teacher("Lopez", "Math", 37));

        return classRoom;
    }
}
static void Main(string[] args)
    {
        var classRoom = Create.ClassRoom();

        Console.WriteLine("Students: ");
        foreach (var student in classRoom.Students)
        {
            Console.WriteLine("Name: {0}; Age: {1}", student.Name, student.Age);
        }

        Console.WriteLine("Teachers: ");
        foreach (var teacher in classRoom.Teachers)
        {
            Console.WriteLine("Name: {0}; Subject: {1}", teacher.Name, teacher.Subject);
        }
    }

“教室”的函数定义在哪里?哎呀!对不起,忘记切换名称了。我现在就编辑它。您应该先创建类的实例。类似于“教室myClass=new课堂()”的内容,然后通过类似于myClass.getNumberOfStudents()的内容访问它的方法