的我来到了这个网站(http://snipplr.com/view.php?codeview&id=17637),这说明像这样使用反射:C#和使用反射
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));
}
}
的codesnippet上述会给你: 年龄:30 名称:托尼·蒙大拿
如果我们增加了“小子”的类“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 名称:托尼·蒙大拿 小子:ProjectName.Form1 +儿童
不太什么,我一直在寻找....我可以使用反射来遍历低谷“孩子“呢?建议?
对'kid'对象做同样的事情 – I4V 2013-05-13 13:43:31
您是否真的对某种形式的序列化感兴趣,比如JSON? http://json.codeplex.com/ – 2013-05-13 13:43:43
你将需要递归调用你的输出方法,并期待看看一个属性是否是一个对象,我相信这个问题做到了这一切:http://stackoverflow.com/questions/6196413/ how-to-recursively-print-the-values-of-an-objects-properties-using-reflection – gordatron 2013-05-13 13:44:55