gpt4 book ai didi

c# - 将动态对象转换为 NameValueCollection

转载 作者:行者123 更新时间:2023-11-30 14:28:50 26 4
gpt4 key购买 nike

如何将动态转换为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com