修改C#字典值

min*_*ang 5 c# collections data-structures

我是C++专家,但对C#来说根本不是.我创建了一个Dictionary<string, STATS>,STATS简单的地方struct.一旦我用initial stringSTATSpairs 构建了字典,我想修改字典的STATS值.在C++中,它非常清楚:

Dictionary<string, STATS*> benchmarks;
Initialize it...

STATS* stats = benchmarks[item.Key];
// Touch stats directly
Run Code Online (Sandbox Code Playgroud)

但是,我在C#中尝试过这样的:

Dictionary<string, STATS> benchmarks = new Dictionary<string, STATS>();

// Initialize benchmarks with a bunch of STATS
foreach (var item in _data)
  benchmarks.Add(item.app_name, item);

foreach (KeyValuePair<string, STATS> item in benchmarks)
{
  // I want to modify STATS value inside of benchmarks dictionary.
  STATS stat_item = benchmarks[item.Key];
  ParseOutputFile("foo", ref stat_item);

  // But, not modified in benchmarks... stat_item is just a copy.
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常新手的问题,但不容易找到答案.

编辑:我也尝试过如下:

  STATS stat_item = benchmarks[item.Key];
  ParseOutputFile(file_name, ref stat_item);
  benchmarks[item.Key] = stat_item;
Run Code Online (Sandbox Code Playgroud)

但是,我得到了异常,因为这样的动作使Dictionary无效:

Unhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
  at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
  at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
  at helper.Program.Main(String[] args) in D:\dev\\helper\Program.cs:line 75
Run Code Online (Sandbox Code Playgroud)

Dan*_*Tao 10

如果你STATS的确是一个struct,这意味着它是一个值类型,所以你这样做:

STATS stat_item = benchmarks[item.Key];
ParseOutputFile("foo", ref stat_item);
Run Code Online (Sandbox Code Playgroud)

stat_item是位于的值的副本benchmarks[item.Key].因此,当您将其作为ref参数传递给时ParseOutputFile,仅修改副本.

在您发布的C++代码中,请注意您将使用指针执行您要在此处完成的操作.

对于.NET,解决方案很简单:更改STATS引用类型(class而不是struct).然后,您的局部stat_item变量将引用由值引用的同一对象benchmarks[item.Key].