2013-08-20 86 views
0

我有一個方法,返回一個動態創建的對象,並希望添加字典的鍵作爲此對象的動態屬性和字典值作爲值這個新對象的屬性。下面是方法,但沒有成功,有人幫助我理解並做到這一點?將字典值添加到動態對象在c#

*不是詞典對象是與字典

public Object setObjectProperty(Dictionary<String, String> dictionary) 
{ 
    dynamic newObj = new ExpandoObject(); 

    foreach (var word in dictionary) 
    { 
     newObj.word.Key = word.Value; 
    } 

    return (Object) newObj; 
} 

回答

1

ExpandoObject實現IDictionary<string, object>的值(鍵和值)的對象,但它明確地實現這些方法。只需將其轉換爲該類型,然後即可訪問Add方法:

public static Object setObjectProperty(Dictionary<String, String> dictionary) 
{ 
    IDictionary<string, object> newObj = new ExpandoObject(); 

    foreach (var word in dictionary) 
    { 
     newObj.Add(word.Key, word.Value); 
    } 

    return newObj; 
}