![](/img/trans.png)
[英]How do I correctly parse a URI query string into a name-value collection in C#?
[英]C# How do I correctly return this collection?
我正在嘗試學習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();
}
}
public ReadOnlyCollection<ServerInformation> GetServers()
{
return new ReadOnlyCollection<ServerInformation>(servers);
}
您不能將屬性用作泛型類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.