2012-08-22 5 views
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"); 

그러나 : 그들은 내가이 호출의 두 번째 매개 변수를 지정해야한다고 말했다 곳

나는 인터넷에 어떤 기사를 읽었습니다.

도움이 되시길 바랍니다.

미리 감사드립니다.

+0

? 귀하의 코드는 나를 위해 잘 작동합니다. –

+0

t는 키가 문자열 또는 십진수가 될 수있는 사전이고 값은 다른 유형이 될 수 있습니다. – tesicg

+0

't.ToString()'의 결과를 보여주십시오. 사전이 하나의'Remove' 메소드만을 가지고 있으므로 예외가 발생하지 않아야 정상적인 사전이 될 수 있습니다. 따라서 여기에 모호성이 없습니다 ... –

답변

1

이 시도 :

`t`의 유형이 무엇
var genericArguments = cacheItem.Value.GetType().GetGenericArguments(); 
var keyType = genericArguments[0]; // Maybe implement some error handling. 
MethodInfo info = t.GetMethod("Remove", new [] { keyType }); 
+0

그것은 작동합니다! 정말 고맙습니다! :) – tesicg

관련 문제