This may have been asked many times, and I've been searching around, but for some reason, this doesn't make sense to me. So it seems like I create a new instance, but Visual studio tells me that Object reference not set to an instance of an object.
public class Test{
private Dictionary<string, Service> serviceList;
private void GetList(string ID){
foreach(var service in Service.Load()){
servicelist.Add(service.ID, new Service());
}
}
}
I think when I use new Service(), I basically create a new instance of the Service every single time I move to the next element in the Dictionary? Service is a class
You forgot to instantiate your list, you need:
private Dictionary<string, Service> serviceList = new Dictionary<string, Service>();
private void GetList(string ID){
....
To answer your initial question: Yes, a new instance is created for each item in the collection being iterated over.
you are just declaring the dictionary you need to initialize it
do this
private Dictionary<string, Service> serviceList = new Dictionary<string, Service>();
Yes. That exactly you do. When you call new Service ()
you create a new instance of the class, except if Service is a singleton class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.