【发布时间】:2014-11-26 22:03:11
【问题描述】:
我在尝试修改 ConcurrentDictionary 中的项目时遇到非常奇怪的错误:
private ConcurrentDictionary<string, Tripple> SeenEnoughDict =
new ConcurrentDictionary<string, Tripple>();
private struct Tripple
{
public int prev_antenna;
public int num_of_times_seen;
public Timer timer;
// ctor
public Tripple(int antenna, Timer tm)
{
this.prev_antenna = antenna;
this.num_of_times_seen = 1;
this.timer = tm;
}
}
// several items were added to the dictionary
Parallel.ForEach(_myReaderTC.Cast<Tag>(), t => {
// attempting to modify the item
// t.ID is string
SeenEnoughDict[t.ID].num_of_times_seen = SeenEnoughDict[t.ID].num_of_times_seen + 1;
}
最后一行抛出错误:
Error 149 Cannot modify the return value of
'System.Collections.Concurrent.ConcurrentDictionary<string,Tripple>.this[string]'
because it is not a variable
这个错误的有趣之处在于http://pastebin.com/0cQJMcUD 可以正常工作。 最近,我将我的解决方案从 2010 年转换为 2013 年。在 2010 年,我使用了从 .NET 4 向后移植到 3.5(我从 NuGet 获得)的并发集合。
【问题讨论】:
-
尝试将返回值设为一个类。我会是你可以修改它的值。编译器在这里为您提供帮助,因为您正在返回一个结构并对其进行修改,您不会像您认为的那样获得值更新。
-
由于这个原因,创建可变结构通常不是一个好主意。我建议您使用由私有 fields 支持的公共 properties,而不是公开公开这些字段 - 并开始遵循 .NET 命名约定。
-
@focuspark - 如果你能把它写成答案。我很乐意接受。
-
@newprint Adam Robinson 在下面写了一篇很棒的文章,供您标记为答案。无论如何谢谢:-)
标签: c# .net concurrency