我是C++专家,但对C#一点也不感兴趣。我创建了一个Dictionary<string, STATS>,其中STATS是一个简单的struct。一旦我用初始的string和STATS对构建了字典,我想要修改字典的STATS值。在C++中,非常清楚:
Dictionary<string, STATS*> benchmarks;
Initialize it...
STATS* stats = benchmarks[item.Key];
// Touch stats directly然而,我在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.
}这确实是一个新手的问题,但很难找到答案。
编辑:我也尝试了如下方法:
STATS stat_item = benchmarks[item.Key];
ParseOutputFile(file_name, ref stat_item);
benchmarks[item.Key] = stat_item;但是,我得到了一个例外,因为这样的操作会使字典无效:
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发布于 2010-03-13 08:01:37
如果您的STATS确实是一个struct,这意味着它是一个值类型的,那么您可以这样做:
STATS stat_item = benchmarks[item.Key];
ParseOutputFile("foo", ref stat_item);您的stat_item是位于benchmarks[item.Key]的值的副本。因此,当您将它作为ref参数传递给ParseOutputFile时,只有复制会被修改。
在您发布的C++代码中,请注意,您将通过使用指针来完成您在这里试图完成的任务。
对于.NET,解决方案很简单:将STATS更改为引用类型( class而不是struct)。然后,本地stat_item变量将是对由benchmarks[item.Key]值引用的同一个对象的引用。
发布于 2010-03-13 08:01:45
您应该将STATS更改为一个类。这样就不需要ref关键字,对象就会改变。
在C#中,通常的建议是使用类,除非绝对确定您需要一个结构。
发布于 2010-03-13 07:57:25
试试这个:
STATS stat_item = benchmarks[item.Key];
ParseOutputFile("foo", ref stat_item);
benchmarks[item.Key] = stat_item;注意,即使STATS是一个类,那么更新引用(正如ref关键字所暗示的那样)只会更新本地引用stat_item,而不会更新字典中的值。
例如,如果STATS是一个类,下面的代码将修改字典中的值(但在本例中,不需要ref关键字,应该删除该关键字):
ParseOutputFile(string foo, ref STATS statItem)
{
statItem.SomeProperty = ...
}但是,以下内容只会影响局部变量,不会更新字典值,即使STATS是类:
ParseOutputFile(string foo, ref STATS statItem)
{
statItem = new STATS();
...
}https://stackoverflow.com/questions/2437691
复制相似问题