0

我有一个方法,它返回一个动态创建的对象,并想将字典的键添加为该对象的动态属性,并将字典值添加为该新对象的属性值。以下是方法,但没有成功,有人帮我理解并做到这一点吗?

* is not a dictionary object 是具有字典的值(键和值)的对象

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

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

    return (Object) newObj;
}
4

1 回答 1

2

ExpandoObjectimplements 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;
}
于 2013-08-20T21:00:17.123 回答