列表中的类属性c#赋值

时间:2014-08-04 09:36:23

标签: c# asp.net winforms c#-4.0 console

class Program
{
    static void Main(string[] args)
    {
        Posting onjPosting = null;
        List<Posting> objList = null;

        for (int i = 0; i < 100; i++)
        {
            onjPosting = new Posting();
            onjPosting.Key1 = i;
            for (int j = 0; j < 5; i++)
            {
                Choice objChoice = new Choice();
                objChoice.ID = i;
                objChoice.VAL = j;

                onjPosting.GetPostingChoice.Add(objChoice); // GETTING ERROR [ Object reference not set to an instance of an object. ] 

            }
            objList.Add(onjPosting);
        }
    }
}


public class Choice
{
    public int ID { get; set; }
    public int VAL { get; set; }
}    
public class Posting
{

    public int Key1 { get; set; }        
    public List<Choice> GetPostingChoice { get; set; }

}

循环并分配值时,我收到错误。怎么解决这个?请帮帮我。

我的要求是一个父类(Posting),可以包含多个数据List。

提前致谢。

2 个答案:

答案 0 :(得分:3)

您永远不会分配GetPostingChoice列表,因此它当然是空的。

您可以在构造函数中执行此操作:

public class Posting
{
    public Posting()
    {
        GetPostingChoice = new List<Choice>();
    }

    public int Key1 { get; set; }        
    public List<Choice> GetPostingChoice { get; set; }
}

答案 1 :(得分:2)

Posting班级添加公开构造函数:

public class Posting
{

    public int Key1 { get; set; }        
    public List<Choice> GetPostingChoice { get; set; }
    public Posting()
    {
        GetPostingChoice = new List<Choice>();
    }
}

您还有其他错误:

  1. 您没有初始化objList,因此无法添加。

    List<Posting> objList = null;
    

    所以当你到达时,你会得到另一个Null参考:

    List<Posting> objList = null;
    
  2. 在你的第二个循环中,你增加i而不是j,所以它永远不会结束。

    for (int j = 0; j < 5; i++)
    
  3. 这应该是它的样子:

    Posting onjPosting = null;
    List<Posting> objList = new List<Posting>();
    
    for (int i = 0; i < 1; i++)
    {
        onjPosting = new Posting();
        onjPosting.Key1 = i;
        for (int j = 0; j < 5; j++)
        {
            Choice objChoice = new Choice();
            objChoice.ID = i;
            objChoice.VAL = j;
    
            onjPosting.GetPostingChoice.Add(objChoice); // GETTING ERROR [ Object reference not set to an instance of an object. ] 
    
        }
        objList.Add(onjPosting);
    }
    

    既然你要求采用另一种方法,而这只是你可以做到的众多方法之一,请看看:

    List<Posting> objList = new List<Posting>();
    Enumerable.Range(0,100)
    .Select
    (
        (x,i)=>new Posting
        {
            Key1 = i,
            GetPostingChoice = Enumerable.Range(0,5).Select((p,j)=>new Choice{ID = i,VAL = j}).ToList()
        }
    );