如何将动态转换为 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;
}
最佳答案
我找到了答案:
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
}
关于c# - 将动态对象转换为 NameValueCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28023361/