运行以下代码时c#中的空引用异常

时间:2013-12-25 07:10:50

标签: c# nullreferenceexception

我只是一个学习者。我正在获取以下代码段的空引用异常。请更正错误并告诉我此代码有什么问题。

  class Program
    {
        static void Main(string[] args)
        {
            Company objcompany = new Company();

            Employee obj1 = new Employee(101, "Test1");
            Employee obj2=  new Employee(102, "Test2");
            Employee obj3 = new Employee(103, "Test3");

            objcompany.EmpList.Add(obj1);
            objcompany.EmpList.Add(obj2);
            objcompany.EmpList.Add(obj3);

            foreach (var emp in objcompany.EmpList)
            {
                Console.WriteLine(emp.EmpId + " " + emp.EmpName);
            }

            Console.ReadKey();
        }
    }

    class Company
    {
        public List<Employee> EmpList { get; set; }
    }

    class Employee
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }

        public Employee(int empid, String empname)
        {
            this.EmpId = empid;
            this.EmpName = empname;
        }
    }

我创建了3个类。[Employee,Company,Program]。我想将员工添加到集合中。我正在处理程序类中的代码。

1 个答案:

答案 0 :(得分:1)

您尚未初始化EmpList。我建议你在 Company 类构造函数

中初始化它
class Company
{
    public Company()
    {
         EmpList = new List<Employee>();
    }
    public List<Employee> EmpList { get; set; }
}