向@MikeH致敬,
如果您的意图是迭代纯对象,以获得变量名作为键,其值作为值,那么您可以使用反射来实现这一点。下面是一个例子
public class Test
{
public string Prop1 {get; set;}
public string Prop2 {get; set;}
public string Prop3 {get; set;}
public string Prop4 {get; set;}
}
public class Program
{
public static void Main()
{
var test = new Test(){
Prop1 = "Test1",
Prop2 = "Test2",
Prop3 = "Test3",
Prop4 = "Test4"
};
foreach (var property in test.GetType().GetProperties())
{
Console.WriteLine("{0} = {1}", property.Name, property.GetValue(test));
}
}
}
此外,如果你想再使用字典,你可以使用
var dict = test.GetType().GetProperties().ToDictionary(x => x.Name, x=> x.GetValue(test));
foreach (var key in dict.Keys)
Console.WriteLine("{0} = {1}", key, dict[key]);