我是一位正在將C++代碼轉換爲C#的新手。我有一個地圖訪問C#詞典中的元素
map<string, Object*> table;
和功能
void define(const string& symbol, Object* definition)
{
map<string, Object*>::iterator iter = table.find(symbol);//returns iterator to element with key "symbol," else sets equal to map::end
if (iter != table.end())//if key is in map
{
delete (*iter).second;
table.erase(iter);
}
table.insert(pair<string, Object*>(symbol,definition->clone()));
}
,我要創建C#中的等價功能。我創建了一個解釋:
private Dictionary<string, Object> table = new Dictionary<string, Object>();
,這裏是我的功能至今
public void define(string symbol, Object definition)
{
if (table.ContainsKey(symbol))
{
//function body
}
,現在需要我的函數體來完成同樣的事情。從我的研究來看,它似乎不像C#具有相同的迭代器結構。
小心。 C++和C#中的許多東西看起來很相似,但處理方式完全不同。值得注意的是,確保你理解C++和C#中值,指針和引用的處理之間的差異;在這個代碼片段中,我可以看到你'刪除了之前存在的值,並將其替換爲作爲參數傳遞的值的克隆。確保你理解這背後的原因--xanatos的答案在C#中可能非常好,但它也可能完全錯誤。當然,你真的*想要使用'object'嗎?這有點可疑。 – Luaan
請注意,C++只是很複雜,因爲它愚蠢地嘗試使用原始指針來管理內存。使用更明智的映射類型('Object',或可能'unique_ptr