2

我有一本字典,其中的键可以是字符串或十进制。这些值可以是不同类型的对象。我想编写可以在所有情况下管理删除字典项的代码。

我要替换的代码如下:

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");

但是,我不知道该怎么做。

任何帮助表示赞赏。

先感谢您。

4

1 回答 1

1

尝试这个:

var genericArguments = cacheItem.Value.GetType().GetGenericArguments();
var keyType = genericArguments[0]; // Maybe implement some error handling.
MethodInfo info = t.GetMethod("Remove", new [] { keyType });
于 2012-08-22T12:22:41.220 回答