创建Computer对象存入列表无输出及对象列表未存条目的问题
Troubleshooting Your Computer Object & List Issues
Hey there, let's work through your two problems and get things working properly!
Issue 1: Object List Won’t Store Entries or Display Content
The most common reason for this is not initializing your list correctly. If you only declare a List<Computer> variable without creating a new instance of the list, adding items will either fail silently or throw a null reference error.
Fix Example:
// Initialize the list properly before adding items List<Computer> computerInventory = new List<Computer>(); // Add a fully constructed Computer object to the list computerInventory.Add(new Computer("Dell", "HQ Server Room", "SRV-01", "PC-123", "2024-05-20 14:30"));
Also double-check that you’re not trying to add a null Computer object to the list—every entry needs to be a fully instantiated instance using your constructor.
Issue 2: No Output When Viewing Computer Object Data
Looking at your partial class code, two key issues are causing this:
- Your class properties (
companyName,locationName, etc.) are private by default, so you can’t access their values outside the class. - You haven’t overridden the default
ToString()method, so printing the object will just show the type name instead of meaningful data.
Fixed Computer Class Code:
class Computer { // Make properties publicly accessible (using get-only properties for immutability) public string CompanyName { get; } public string LocationName { get; } public string ServerName { get; } public string DeviceName { get; } public string LastOnline { get; } // Complete constructor to set all properties public Computer(string companyName, string locationName, string serverName, string deviceName, string lastOnline) { CompanyName = companyName; LocationName = locationName; ServerName = serverName; DeviceName = deviceName; LastOnline = lastOnline; } // Override ToString() to display human-readable data when printing the object public override string ToString() { return $"Device: {DeviceName} | Company: {CompanyName} | Location: {LocationName} | Last Online: {LastOnline}"; } }
How to View the Data Now:
- Print a single Computer object:
Computer myPC = new Computer("HP", "Remote Office", "SRV-02", "PC-456", "2024-05-20 15:15"); Console.WriteLine(myPC); // Uses our custom ToString() output - Loop through your list to display all entries:
foreach (var computer in computerInventory) { Console.WriteLine(computer); }
Quick Recap
- Always initialize your list with
new List<Computer>()before adding items. - Make class properties accessible (public or with getters) to read their values outside the class.
- Override
ToString()to get useful output when printing objects.
内容的提问来源于stack exchange,提问作者Ollie Beumkes
相关产品推荐
相关产品推荐

