2
我有一個字典,其中的鍵可以是字符串或小數。這些值可以是不同類型的對象。我想編寫可以管理在所有情況下刪除字典項目的代碼。C#:如何使用反射從字典中刪除項目?
我想更換代碼如下:
ConcurrentDictionary<string, Parus.Metadata.Units.Unit> objDict = cacheItem.Value as ConcurrentDictionary<string, Parus.Metadata.Units.Unit>;
foreach (var detaildGrid in this.MasterGridFrameControl.ChildFrames)
{
foreach (GridDataItem item in detaildGrid.GridControl.SelectedItems)
{
object dataKey = item.GetDataKeyValue("SubKey");
objDict.Remove((string)dataKey);
}
}
或者如下:
ConcurrentDictionary<decimal, Domain> objDict = cacheItem.Value as ConcurrentDictionary<decimal, Domain>;
foreach (GridFrameControl detaildGrid in this.MasterGridFrameControl.ChildFrames)
{
foreach (GridDataItem item in detaildGrid.GridControl.SelectedItems)
{
object dataKey = item.GetDataKeyValue("SubKey");
objDict.Remove((decimal)dataKey);
}
}
代碼應如下所示:
foreach (GridDataItem item in detaildGrid.GridControl.SelectedItems)
{
object dataKey = item.GetDataKeyValue("SubKey");
object[] parameters = { dataKey };
Type t = cacheItem.Value.GetType();
MethodInfo info = t.GetMethod("Remove");
info.Invoke(cacheItem.Value, parameters);
}
但是,我收到此錯誤消息:找到了不明確的匹配項。
MethodInfo info = t.GetMethod("Remove");
但是,我不知道如何做到這一點:
,他們說我應該指定該呼叫的第二個參數我讀過一些網絡上的文章。
任何幫助表示感謝。
預先感謝您。
是什麼在't'類型?你的代碼適合我。 –
t是字典,其中鍵可以是字符串或小數,值可以是不同的類型。 – tesicg
請讓我看看't.ToString()'的結果。如果它是一個正常的字典,你不應該得到這個異常,因爲字典只有一個'Remove'方法,所以在那裏沒有歧義... –