0

我有一本字典

public static IDictionary<string, IList<string>> checksCollection = 
           new Dictionary<string, IList<string>>();

我在字典中添加如下:

public static void addCheck(string checkName, string hostName, 
          string port, string pollInterval, string alertEmail, 
          string alertSMS, string alertURI)
{
    checksCollection.Add(checkName, new[] { checkName, hostName, port, 
               pollInterval, alertEmail, alertSMS, alertURI });
}

如何更改alertURI列表值?

4

2 回答 2

1

最快的方法是IList<string>从字典中获取并访问它的第七个元素:

checksCollection[checkName][6] = "new value";

但如果我是你,我会将字符串数组中的所有这些值设为自己的类,这样你就不必对索引值进行硬编码,以防万一将来添加或删除其他属性。像这样创建一个类定义:

public class YourClass
{
    public string CheckName { get; set; }
    public string HostName { get; set; }
    public string Port { get; set; }
    public string PollInterval { get; set; }
    public string AlertEmail { get; set; }
    public string AlertSMS { get; set; }
    public string AlertURI { get; set; }
}

并更改您的字典定义:

public static IDictionary<string, YourClass> checksCollection = 
    new Dictionary<string, YourClass>();

然后添加到它(虽然最好你会创建一个YourClass带参数的构造函数):

public static void addCheck(string checkName, string hostName, string port, string pollInterval, string alertEmail, string alertSMS, string alertURI)
{
    checksCollection.Add(checkName, new YourClass() { 
        CheckName = checkName,
        HostName = hostName,
        Port = port,
        PollInterval = pollInterval,
        AlertEmail = alertEmail,
        AlertSMS = alertSMS,
        AlertURI = alertURI
    });
}

然后修改变得简单,无需猜测数组索引:

checksCollection[checkName].AlertURI = "new value";
于 2012-06-16T14:41:47.870 回答
0

一种方法是做

checksCollection["somekey"][6] = "new value for alertURI"

我建议创建一个代表这 7 个值的小对象,例如

class Foo {
    public string HostName { get; set; }
    public string Port { get; set; }
    public string PollInterval { get; set; }
    public string AlertEmail { get; set; }
    public string AlertSMS { get; set; } 
    public string AlertURI { get; set; }
}

然后你可以改变它

checksCollection["key"].AlertURI = "something else";
于 2012-06-16T14:41:37.960 回答