添加到列表中的类中 [英] Adding to a list inside a class

查看:103
本文介绍了添加到列表中的类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个类

public class User
{
   private string _name;
   public string UserName { get; set; }       
   public List<int> ControlNumber { get; set; }
   public User (string username)
   {
       _name = username;
   }
   public User()
   {
   }

}

和此功能,填补了类。

User UserClass = new User(e.Key); //e.Key = user's name

public static void FillUserListClass(DataTable dt, ref UserClass)

{
    try
    {

        for (int ctr = 0; ctr < dt.Rows.Count; ctr++)
        {
            var row = dt.Rows[ctr];
            var userName = row["User"].ToString();

            if (UserList.ContainsKey(userName))
            {
                UserList[userName].Add(Convert.ToInt32(row["ControlNumber"]));
            }
            else
            {
                _user.UserName = row["User"].ToString();
                _user.ControlNumber.Add(Convert.ToInt32(row["ControlNumber"]));

            }
              //print out
            Console.WriteLine("UserList Class: ");
            Console.WriteLine(_user.UserName);
            Console.WriteLine(_user.ControlNumber);


        }
    }
    finally
    {
        //conn.Close();
    }

}



然而,在 _user.ControlNumber.Add(Convert.ToInt32(行[控制编号])); 行,我得到了对象引用不设置到对象的实例。错误。任何帮助吗?

However, at the _user.ControlNumber.Add(Convert.ToInt32(row["ControlNumber"])); line I get the "Object reference not set to an instance of an object." error. Any help?

我想要做的就是创建一个类,它包含了用户的控制编号每个用户。然后,我想所有这些类被放入一本字典,以供参考。

What i'm trying to do is create a class for each user that contains the user's control numbers. I then want all of these classes to be placed into a dictionary for reference.

推荐答案

您需要初始化在构造函数列表

You need to initialize your list in the constructor:

   public User (string username) : this()
   {
       _name = username;
   }
   public User()
   {
      this.ControlNumber = new List<int>();
   }



另外,控制编号将拥有空的默认值。

这篇关于添加到列表中的类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆