我是C++專家,但對C#沒有任何幫助。我創建了Dictionary<string, STATS>
,其中STATS
是一個簡單的struct
。一旦我用string
和STATS
對創建字典,我想修改字典的STATS
值。在C++中,這是非常清楚的:修改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
呃,你應該在C++世界中留下那些大寫字母。它在C#中看起來很糟糕。微軟的命名準則建議使用Pascal案例。 – 2010-03-13 07:59:55
結構是值類型,因此這是相同的,然後聲明一個本地雙重,因此新的stat_item是字典記錄的副本。如果STATS是一個類,那麼它是一個參考,然後它會起作用。 – weismat 2010-03-13 08:01:38
這是一個非常簡單的玩具解析程序。 :D實際上,我仍然喜歡用Windows C++風格編寫代碼,但現在我不得不遵循Google的指南......對不起! – minjang 2010-03-13 08:08:16