C#如何正确返回此集合?

时间:2014-09-10 01:06:48

标签: c#

我正在尝试学习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;
    }
}

2 个答案:

答案 0 :(得分:3)

您的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();
    }
}

答案 1 :(得分:2)

public ReadOnlyCollection<ServerInformation> GetServers()
{
    return new ReadOnlyCollection<ServerInformation>(servers);
}

您不能将属性用作通用类型