遍历dynamic的方式

一、遍历ExpandoObject

/// 
/// 遍历ExpandoObject
/// 
[TestMethod]
public void GoThroughExpandoObject()
{
    dynamic dynEO = new ExpandoObject();
    dynEO.number = 10;
    dynEO.Increment = new Action(() => { dynEO.number++; });

    Console.WriteLine(dynEO.number);
    dynEO.Increment();
    Console.WriteLine(dynEO.number);

    //dynEO.number 中number是动态添加属性。
    //dynEO.Increment 中Increment 是动态添加的Action 委托。

    //枚举ExpandoObject的所有成员:

    foreach (var property in (IDictionary)dynEO)
    {
        Console.WriteLine(property.Key + ": " + property.Value);
    }
}

二、对于dynamic是反序列化得到的对象时:

    dynamic expando = JsonConvert.DeserializeObject<dynamic>(requestMessage);
    // 将ExpandoObject转换为SortedDictionary
    SortedDictionary<string, string> dic = new SortedDictionary<string, string>();

    foreach (var property in expando)
    {
        dic.Add(property.Name.ToLower(), property.Value.ToString());
    }

 

你可能感兴趣的:(遍历dynamic的方式)