Skip to main content
 首页 » 编程设计

C# 如何正确返回此集合

2024年02月01日31hnrainll

我正在尝试学习 C#,但我不明白为什么会出现错误。我收到错误 “ServerList.servers' is a 'property' but is used like a 'type'”。我读过几条准则,指出我不应该有一个可公开访问的列表,这就是我尝试使用一种方法返回服务器列表的原因。

如何正确返回“服务器”集合?我这样做完全错了吗?另外,我的代码还有什么问题吗?

class Program 
{ 
    static void Main() 
    { 
        ServerList list = new ServerList(); 
        list.AddServer("server", "test1", "test2"); 
    } 
} 
 
public class ServerInformation 
{ 
    public string Name { get; set; } 
    public string IPv4 { get; set; } 
    public string IPv6 { get; set; } 
} 
 
public class ServerList 
{ 
    private List<ServerInformation> servers { get; set; } 
 
public ServerList() 
{ 
    servers = new List<ServerInformation>; 
} 
 
    public void AddServer(string name, string ipv4, string ipv6) 
    { 
        servers.Add(new Server { Name = name, IPv4 = ipv4, IPv6 = ipv6 });   
    } 
 
    public ReadOnlyCollection<servers> GetServers() 
    { 
        return servers; 
    } 
} 

请您参考如下方法:

您的ServerList 类有几个问题。我为每一个都添加了注释,指出您的代码的内容以及下面的更正版本。

public class ServerList 
{ 
    private List<ServerInformation> servers { get; set; } 
 
    public ServerList() 
    { 
        //servers = new List<ServerInformation>; 
        // constructor must include parentheses 
        servers = new List<ServerInformation>();  
    } 
 
    public void AddServer(string name, string ipv4, string ipv6) 
    { 
        //servers.Add(new Server { Name = name, IPv4 = ipv4, IPv6 = ipv6 }); 
        // Server does not exist, but ServerInformation does 
        servers.Add(new ServerInformation { Name = name, IPv4 = ipv4, IPv6 = ipv6 });   
    } 
 
    //public ReadOnlyCollection<servers> GetServers() 
    // The type is ServerInformation, not servers. 
    public ReadOnlyCollection<ServerInformation> GetServers() 
    { 
        //return servers; 
        // servers is not readonly 
        return servers.AsReadOnly(); 
    } 
}