Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 添加到viewmodel中的icollection_C# - Fatal编程技术网

C# 添加到viewmodel中的icollection

C# 添加到viewmodel中的icollection,c#,C#,我的“UserViewModel”中有一个ICollection: public ICollection<userpractice> userpractices { get; set; } 我收到一个错误,说“对象引用未设置为对象的实例”。我不知道为什么,因为up肯定正确地分配给了填充的userpractice 如果有帮助,uservm.userpractices为null。但是我认为一开始应该是空的,因为viewmodel在集合中没有任何用户实践 是的,uservm.userpr

我的“UserViewModel”中有一个ICollection:

public ICollection<userpractice> userpractices { get; set; }
我收到一个错误,说“对象引用未设置为对象的实例”。我不知道为什么,因为up肯定正确地分配给了填充的userpractice


如果有帮助,uservm.userpractices为null。但是我认为一开始应该是空的,因为viewmodel在集合中没有任何用户实践

是的,
uservm.userpractices
一开始是
null
是非常正常的。这就是为什么在向集合添加项之前需要创建集合的新实例。例如:

List<string> items;
items.Add("test"); //Object reference exception
列表项;
项目。添加(“测试”)//对象引用异常
首先要做到:

items = new List<string>();
items.Add("test"); //works
items=新列表();
项目。添加(“测试”)//作品

是的,
uservm.userpractices
一开始是
null
是非常正常的。这就是为什么在向集合添加项之前需要创建集合的新实例。例如:

List<string> items;
items.Add("test"); //Object reference exception
列表项;
项目。添加(“测试”)//对象引用异常
首先要做到:

items = new List<string>();
items.Add("test"); //works
items=新列表();
项目。添加(“测试”)//作品

这是因为您尚未创建集合的实例,请更新您的
UserViewModel
构造函数以执行
this.userpractices=new List()
。这是因为您尚未创建集合的实例,请更新
UserViewModel
构造函数以执行
this.userpractices=new List()
。这对我来说非常有效,不必因为这个答案而问我的问题。这对我来说非常有效,不必因为这个答案而问我的问题。