C#如何正确返回此集合

本文关键字:集合 返回 何正确 | 更新日期: 2023-09-27 18:21:13

我正在努力学习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;
    }
}

C#如何正确返回此集合

您的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();
    }
}
public ReadOnlyCollection<ServerInformation> GetServers()
{
    return new ReadOnlyCollection<ServerInformation>(servers);
}

不能将属性用作泛型类型