是否可以在Main()之外使用List <t>?

时间:2019-01-28 08:48:09

标签: c# list main

我试图用C#创建一个简单的数据输入系统(仅用于自学),并试图理解List。 我制作了一个用于数据输入的简单控制台系统,插入了学生和教师(具有标题,姓名,姓氏,出生日期,经过授课的或经过学习的课程等)。我还想做的是将每个新创建的人(老师或学生)及其唯一编号添加到数组中。然后我发现了列表。现在这是我的问题:

我有一个人基班和一个继承的老师,学生班。在Main中,我可以创建一个新的var stu1,创建一个名为Studentslist的列表,然后将stu1,stu2,stuX添加到该列表中。我可以访问列表,等等。

但是我想在学生班上这样做。如果我在构造函数中执行此操作,它将创建“学生列表”。但是当我使用addStu来列出方法(Student类中我自己的方法)或在列表创建后立即添加它(我尝试了几种不同的方法)时,我可以看到数据进入了列表但是当我在main中调用它时,列表将为null,我会得到

  

System.NullReferenceException:'对象引用未设置为实例   对象的

这是我的代码:

public Student(string title, string name, string surname, string dob, string degreename = "") : base(title, name, surname, dob)
    {

        if (stucount == 0) // if this is the very first student, create the list Studentslist for the very first time AND and the very first student to the list
        {
            stucount++;
            List<string> Studentslist = new List<string>();
            Studentslist.Add(this.getStuIDtitleNameSurname()); // this part goes OK, however if I try access this from Main, it will throw System.NullReferenceException

        }
        else
        { stucount++;

            string studat = this.getStuIDtitleNameSurname();
            Studentslist.Add(studat); //when I add a another student in Main (I only have one Main, that is in the Program.cs) the code breaks here. 

        }

正如我说的,如果我在Main中执行所有这些操作,那么一切都很好,因为我认为它可以在Main实例中工作。也许我这样做的方式不是应该怎么做。有人可以启发我:)有什么方法可以将其保存在内存/数据库中的某个地方,还是需要在该实例中在Main中进行工作?

1 个答案:

答案 0 :(得分:3)

每个{是一个新范围。因此,要使其起作用,请确保在新作用域之前定义变量。例如在ifswitch等之前

这也适用于类。在名称空间后定义变量,将其置于类级别范围内。

public Student(string title, string name, string surname, string dob, string degreename = "") 
: base(title, name, surname, dob)
{
    //Method level scope
    var Studentslist = new List<string>();

    if (stucount == 0)
    {
        stucount++;
        Studentslist.Add(this.getStuIDtitleNameSurname()); 
    }
    else
    {
        stucount++;
        var studat = this.getStuIDtitleNameSurname();
        Studentslist.Add(studat);
    }
}

提示

  • 在现代编程中,您应始终避免做计数器。如果您觉得这是唯一的解决方案,那么您可能还会遇到其他问题。
  • 您应该保持其简洁和干净。
  • 您应该使用类级别的构造函数来初始化变量。这对于依赖注入尤其重要。
  • 基类也不被接受。它违反了 SOLID 的原则。永远记住Composition over inheritance (他们使用学校/大学的基础来教您关于继承的知识,但是只有在构建框架时,您才这样做,例如,.NET中将时间和考虑因素纳入了继承选择中)

一个更好的版本是...

public int StudentCount => Students.Count;
public List<string> Students => {get; set;}

public Student() {
   Students = new List<string>();
}


public Student(string title, string name, string surname, string dob, string degreename = "") 
: base(title, name, surname, dob)
{
    Studentslist.Add(this.getStuIDtitleNameSurname()); 
}

似乎您正在学习编程,所以建议您阅读《设计模式》一书。

相关问题