我有一个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?
发布于 2013-12-02 08:09:37
出现错误消息的原因是,RosterLine是一个结构,并且是一个值类型。我在意为中遇到的错误是:
无法修改`System.Collections.Generic.SortedDictionary.thisSystem.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成为一个类,也可以像错误消息所建议的那样使用临时变量。
https://stackoverflow.com/questions/20323147
复制相似问题