将动态对象转换为NameValueCollection

时间:2015-01-19 11:15:44

标签: c# asp.net-mvc winforms

如何将动态转换为NameValueCollection?

我尝试将其转换为字典,然后转换为NameValueCollection,但它会为不同类型抛出异常。

[...]
  NameValueCollection item = ((IDictionary<string, object>)dynamicObject).ToNameValueCollection();
[...]

public static NameValueCollection ToNameValueCollection<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
{
  var nameValueCollection = new NameValueCollection();
  foreach (var pair in dictionary)
  {
    string value = pair.Value == null ? null : value = pair.Value.ToString();
    nameValueCollection.Add(pair.Key.ToString(), value);
  }
  return nameValueCollection;
}

1 个答案:

答案 0 :(得分:6)

我找到了答案:

using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.Specialized;

public static class Extensions
{
  public static NameValueCollection ToNameValueCollection<T>(this T dynamicObject)
  {
    var nameValueCollection = new NameValueCollection();
    foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dynamicObject))
    {
      string value = propertyDescriptor.GetValue(dynamicObject).ToString();
      nameValueCollection.Add(propertyDescriptor.Name, value);
    }
    return nameValueCollection;
  }
}

使用它:

public void DoStuff(dynamic obj) 
{
  NameValueCollection items = obj.ToNameValueCollection();
  // Do stuff with items
}