如何遍历字典以获取所有类属性?

时间:2014-01-23 18:23:18

标签: c# dictionary

我正在尝试通过字典循环(button_click中的代码是我正在尝试修复的代码)以获取我的所有类属性。而不是像我的代码一样一个一个地写出它们看起来现在看起来。当前版本工作正常,但如果a应该具有50个或更多属性,我认为必须有一种更简单的方法来执行某种循环。

    class Person
        {
            public int PersNr { get; set; }
            public string Name { get; set; }
            public string BioPappa { get; set; }
            public Adress Adress { get; set; }


            public static Dictionary<int, Person> Metod()
            {
                var dict = new Dictionary<int, Person>();

                dict.Add(8706, new Person
                {
                    Name = "Person",
                    PersNr = 8706,
                    BioPappa = "Dad",
                    Adress = new Adress
                    {
                        Land = "Land",
                        PostNr = 35343,
                        Stad = "city"
                    }
                });

                dict.Add(840, new Person
                {
                    Name = "Person",
                    PersNr = 840,
                    BioPappa = "Erik"
                });
                return dict;

            }

        }

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<int, Person> myDic = Person.Metod();
            var person = myDic[int.Parse(textBoxSok.Text)];

            listBox1.Items.Add(person.Name);
            listBox1.Items.Add(person.PersNr);
            listBox1.Items.Add(person.BioPappa);
            listBox1.Items.Add(person.Adress.Stad);
            listBox1.Items.Add(person.Adress.PostNr);
            listBox1.Items.Add(person.Adress.Land);           
        }
    }

1 个答案:

答案 0 :(得分:0)

让你开始的东西(使用System.Reflection):

private void getProperties(Object obj, ListBox listBox1)
{
    PropertyInfo[] pi = obj.GetType().GetProperties();
    foreach (PropertyInfo p in pi)
    {
        if (p.PropertyType.IsGenericType)
        {
            object o = p.GetValue(obj, null);
            if (o != null)
            {
                if (o is Address)
                    getProperties(o, listBox1);
                else
                    listBox1.Items.Add(o.ToString());
            }
        }
    }
}