Fra*_*man 9 c# anonymous-types
假设我有一个匿名类实例
var foo = new { A = 1, B = 2};
Run Code Online (Sandbox Code Playgroud)
有没有快速生成NameValueCollection的方法?我想获得与下面的代码相同的结果,而不事先知道匿名类型的属性.
NameValueCollection formFields = new NameValueCollection();
formFields["A"] = 1;
formFields["B"] = 2;
Run Code Online (Sandbox Code Playgroud)
Yur*_*ich 22
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()));
Run Code Online (Sandbox Code Playgroud)
另一个(次要)变化,使用静态Array.ForEach方法循环访问属性......
var foo = new { A = 1, B = 2 };
var formFields = new NameValueCollection();
Array.ForEach(foo.GetType().GetProperties(),
pi => formFields.Add(pi.Name, pi.GetValue(foo, null).ToString()));
Run Code Online (Sandbox Code Playgroud)