代码之家  ›  专栏  ›  技术社区  ›  MadBoy

如何创建具有多个值的对象?

  •  0
  • MadBoy  · 技术社区  · 15 年前

    我正在创建一个XML文件,该文件将包含关于TCP连接(IP(字符串)、端口(int)、RetryCount(int)、StartAutomatically(bool)等的几个值。将有许多TcpConnections这样定义(我不知道)。

    我的问题是:

    1. 如何为一个连接分配多个值(最好同时设置所有值并逐个设置)。
    1 回复  |  直到 15 年前
        1
  •  2
  •   Jon Skeet    15 年前

    TcpConnection )具有IP地址、端口、重试次数等属性。

    我建议采用这样的结构:

    public sealed class TcpConnection
    {
        private readonly int port;
        public int Port { get { return port; } }
    
        // Or use one of the types from System.Net
        private readonly string ipAddress;
        public string IpAddress { get { return ipAddress; } }
    
        private readonly int retryCount;
        public int RetryCount { get { return retryCount; } }
    
        // etc
    
        public TcpConnection(XElement element)
        {
            // Extract the fields here
        }
    }
    

    (或者,使用静态工厂方法从XElement中提取值,而构造函数仅获取“原始”值。)

    然后要存储多个值,只需使用 List<TcpConnection> .