Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

c# - Class constructor for list<string> not .add()'ing items

Hey all I am trying to add some values to a list that's within my class constructor.

Issue being is that it does not seem to want to add a string (even though its defined as one) to the list.

This is my current code:

namespace laptopWatcher
{
   public partial class clockCountDown : Window
   {
       public class networkDetails
       {
           public string _ip { get; set; }
           public string _subnetMask { get; set; }
           public string _defaultGateway { get; set; }
           public string _machineName { get; set; }
           public string _hostName { get; set; }
           public string _userName { get; set; }
           public string _userDomainName { get; set; }
           public List<string> _userNames { get; set; }
       }

       private void getUserNames()
       {            
           SelectQuery query = new SelectQuery("Win32_UserAccount");
           ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
           List<string> _tmp = new List<string>();

           foreach (ManagementObject envVar in searcher.Get())
           {
               Console.WriteLine(envVar["Name"].ToString());
               _tmp.Add(envVar["Name"].ToString());
               //theNetwork._userNames.Add(envVar["Name"].ToString());
           }

           theNetwork._userNames.AddRange(_tmp);
       }
   }    
}

The error I am getting is:

System.NullReferenceException: 'Object reference not set to an instance of an object.' laptopWatcher.clockCountDown.networkDetails._userNames.get returned null.

This error is on this line:

theNetwork._userNames.AddRange(_tmp);

That seems correct to me? Odvesley I am missing something or not doing this in the correct order?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

just do it

theNetwork._userNames = new List<string>(_tmp);

and read this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...