0

如何将以下列表添加PosttypeMetas到我的视图模型中?

      static void Main(string[] args)
      {
        List<PosttypeMetas> a = new List<PosttypeMetas>();
        a.Add(new PosttypeMetas { Metatexts = "1", Selects = "mazhar" });
        a.Add(new PosttypeMetas { Metatexts = "2", Selects = "mazhar1" });
        a.Add(new PosttypeMetas { Metatexts = "3", Selects = "mazhar2" });
        a.Add(new PosttypeMetas { Metatexts = "4", Selects = "mazhar3" });
        a.Add(new PosttypeMetas { Metatexts = "5", Selects = "mazhar4" });

        PosttypeVM abc = new PosttypeVM();


        foreach (var listf in a)
        {
            PosttypeMetas abcc = new PosttypeMetas();
            abcc.Metatexts = listf.Metatexts;
            abcc.Selects = listf.Selects;

            abc.posttypemeta.Add(abcc); // NullReferenceException

        }
        Console.Read();         
    }    

public class PosttypeVM
{
    public string module { get; set; }
    public string IsModule { get; set; }
    public string parent { get; set; }    
    public string OrgorSys { get; set; }
    public string ModuleName { get; set; }
    public List<PosttypeMetas> posttypemeta { get; set; }
}

public class PosttypeMetas
{       
    public string Metatexts { get; set; }
    public string Selects { get; set; }
}
4

2 回答 2

2

问题是列表是一个引用类型,它目前什么都没有引用。

您需要先创建列表,然后才能添加。您应该在构造函数中执行此操作:

public PosttypeVM()
{
    posttypemeta = new List<PosttypeMetas>();
}
于 2012-12-13T09:53:56.977 回答
1

由于a已经是List<PosttypeMetas>你不需要foreach循环,只需像这样分配它:

static void Main(string[] args)
      {
        List<PosttypeMetas> a = new List<PosttypeMetas>();
        a.Add(new PosttypeMetas { Metatexts = "1", Selects = "mazhar" });
        a.Add(new PosttypeMetas { Metatexts = "2", Selects = "mazhar1" });
        a.Add(new PosttypeMetas { Metatexts = "3", Selects = "mazhar2" });
        a.Add(new PosttypeMetas { Metatexts = "4", Selects = "mazhar3" });
        a.Add(new PosttypeMetas { Metatexts = "5", Selects = "mazhar4" });

        PosttypeVM abc = new PosttypeVM();
        abc.posttypemeta= a; //assign a to the viewmodel   

        Console.Read();         

    }    

编辑:您将需要实例化列表:

public class PosttypeVM
{


    public string module { get; set; }
    public string IsModule { get; set; }
    public string parent { get; set; }    
    public string OrgorSys { get; set; }
    public string ModuleName { get; set; }
    public List<PosttypeMetas> posttypemeta { get; set; }

    public PosttypeVM(){
     posttypemeta = new List<PosttypeMetas>(); //create the list 
      }
}
于 2012-12-13T09:54:18.563 回答