2012-05-03 3 views
4

사전을받는 방법에 사전을 전달할 수 있습니까?사전 <string, string>을 사전 <object, object> 메서드에 전달할 수 있습니까?

Dictionary<string,string> dic = new Dictionary<string,string>(); 

//Call 
MyMethod(dic); 

public void MyMethod(Dictionary<object, object> dObject){ 
    ......... 
} 
+0

정확한 중복 :

MyMethod(dic.ToDictionary(x => (object)x.Key, x => (object)x.Value)); 

현재 aproach 인해 형태 보증 제한 작동하지 않습니다 http://stackoverflow.com/questions/4734280/how-to-pass-dictarystring-string-object-in-some-method – emd

+0

상황에 따라 다릅니다. 당신은 당신의 방법을 일반적인 것으로 만들 수 있습니까? 인터페이스에 메서드를 넣을 수 있습니까? 다른 해결책이있을 수 있습니다. 제공 한 예가 정확히 필요한 것입니까? –

답변

8

당신은있는 그대로를 전달할 수 없습니다,하지만 당신은 사본 전달할 수 있습니다

var copy = dict.ToDictionary(p => (object)p.Key, p => (object)p.Value); 

그것은 당신의 API 프로그램은 다음과 같이 클래스보다는 인터페이스를 가지고 만들 수있는 좋은 생각이 종종입니다 :

public void MyMethod(IDictionary<object, object> dObject) // <== Notice the "I" 

이 작은 변화는 당신은 당신의 API에 SortedList<K,T> 같은 다른 종류의 사전을 통과 할 수 있습니다. 읽기 전용 목적으로 사전을 전달하려는 경우

1

, 당신은 Linq에 사용할 수 :

public void MyMethod(Dictionary<object, object> dObject){ 
    dObject[1] = 2; // the problem is here, as the strings in your sample are expected 
} 
관련 문제