简体   繁体   English

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

[英]How to loop through a dictionary to get all class-properties?

I'm trying to make a loop through a dictionary (the code in the button_click is the one I'm trying to fix) to get all my class properties. 我试图遍历一本字典(button_click中的代码是我要修复的代码)以获取所有类的属性。 Instead of writing them out one by one like my code look looks now. 现在不再像我的代码一样逐一写出来。 The current version works fine, but if a should have like 50 properties or more, I think there must be a more easy way to do this with some kind of loop. 当前版本可以正常工作,但是如果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);           
        }
    }

Something to get you started (using System.Reflection ): 可以帮助您入门的东西(使用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());
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM