的我來到了這個網站(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