我来到了这个网站(http://snipplr.com/view.php?codeview&id=17637),它说明了反射的使用,如下所示:
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
private void button2_Click_1(object sender, EventArgs e)
{
var person = new Person { Age = 30, Name = "Tony Montana" };
var properties = typeof(Person).GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
}
}
上面的代码片段将为您提供: 年龄:30 姓名:Tony Montana
如果我们像这样将“Kid”添加到“AnotherPerson”类中会怎样
public class Kid
{
public int KidAge { get; set; }
public string KidName { get; set; }
}
public class AnotherPerson
{
public int Age { get; set; }
public string Name { get; set; }
public Kid Kid { get; set; }
}
这个片段;
private void button3_Click(object sender, EventArgs e)
{
var anotherPerson = new AnotherPerson { Age = 30, Name = "Tony Montana", Kid = new Kid { KidAge = 10, KidName = "SomeName" } };
var properties = typeof(AnotherPerson).GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.GetValue(anotherPerson, null));
}
}
给我:年龄:30 姓名:Tony Montana 孩子:ProjectName.Form1+Kid
不完全是我想要的......我可以使用反射来迭代槽“Kid”吗?建议?