1

我有一个 SortedDictionary 定义为:

public SortedDictionary<DateTime,RosterLine> RosterLines = new SortedDictionary<DateTime,RosterLine>();

RosterLine 本身是一个简单的结构:

struct RosterLine {
    public string RosCd;
    public string ActCd;
    public double Hrs;
}

我可以 .Add(dt, rosterLine) 没问题,并且也可以很好地遍历字典。

我的问题是尝试更新给定日期的 RosterLine 值,例如。

DateTime currDt = new DateTime(2013,12,02);
RosterLines[currDt].ActCd = "SO"; // error here

它告诉我:无法修改返回值(此处为字典 def),因为它不是变量。我的目标是用一个迭代循环来做到这一点(我认为这可能是问题所在),但它本身也不会在循环之外工作(如上所述)。

我的问题是:如何使用给定的键(日期)更新 SortedDictionary?

4

1 回答 1

2

错误消息的原因是 RosterLine 是一个结构,并且是一个值类型。我在ideone中遇到的错误是:

无法修改“System.Collections.Generic.SortedDictionary.this[System.DateTime]”的值类型返回值。考虑将值存储在临时变量中

对于值类型,字典存储值的副本,而不是堆上对象的引用。此外,在检索值时(如 中dict[DateTime.Today]),它会再次被复制。因此,以您在示例中所做的方式更改属性仅适用于值类型的副本。编译器通过错误消息防止误解 - 如果它不会想知道为什么 dict 中的值没有改变。

    var dict = new SortedDictionary<DateTime, RosterLine>();
    dict.Add(DateTime.Today, new RosterLine());
    // Does not work as RosterLine is a value type
    dict[DateTime.Today].ActCd = "SO";
    // Works, but means a lot of copying
    var temp = dict[DateTime.Today];
    temp.ActCd = "SO";
    dict[DateTime.Today] = temp;

为了解决这个问题,您可以将 RosterLine 设为一个类,或者您可以按照错误消息的提示使用临时变量。

于 2013-12-02T08:09:37.170 回答