本文介绍了如何将匿名类型的实例转换为NameValueCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

假设我有一个匿名的类实例

Suppose I have an anonymous class instance

var foo = new { A = 1, B = 2};

是否有一种快速的方法来生成NameValueCollection?我想获得与以下代码相同的结果,而无需事先了解匿名类型的属性.

Is there a quick way to generate a NameValueCollection? I would like to achieve the same result as the code below, without knowing the anonymous type's properties in advance.

NameValueCollection formFields = new NameValueCollection();
formFields["A"] = 1;
formFields["B"] = 2;

推荐答案

var foo = new { A = 1, B = 2 };

NameValueCollection formFields = new NameValueCollection();

foo.GetType().GetProperties()
    .ToList()
    .ForEach(pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));

这篇关于如何将匿名类型的实例转换为NameValueCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 02:29